Problems with using example code for Wi-Fi shield (arduino) I have problems with the Wi-Fi shield example code.

#include <SPI.h>
#include <WiFi.h>

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

int status = WL_IDLE_STATUS;
char servername[]="google.com";  // remote server we will connect to

WiFiClient client;

void setup() {
    Serial.begin(9600);
    //disable SD SPI
    pinMode(4, OUTPUT);
    digitalWrite(4, HIGH);

    Serial.println("Attempting to connect to WPA network...");
    Serial.print("SSID: ");
    Serial.println(ssid);

    status = WiFi.begin(ssid, pass);
    if ( status != WL_CONNECTED) {
        Serial.println("Couldn't get a wifi connection");
        // don't do anything else:
        while(true);
        }
     else {
     Serial.println("Connected to wifi");
     Serial.println("\nStarting connection...");
     // if you get a connection, report back via serial:
     if (client.connect(servername, 80)) {
         Serial.println("connected");
         // Make a HTTP request:
         client.println("GET /search?q=arduino HTTP/1.0");
         client.println();
      }
    }
}

 void loop() {

}

The Wi-Fi Shield has connected with the internet Wi-Fi, but the last printing was "Starting connection..." I can't get to connect to (google.com), why?

Have you upgraded the firmware in your wifi shield? If not, it will have problems connecting. Compile and upload this sketch. If it shows the firmware version as 1.0.0, then you need to upgrade the firmware. If it shows 1.1.0, then it is current as of today.

#include <SPI.h>
#include <WiFi.h>

void setup() {
  //Initialize serial and wait for port to open:
  Serial.begin(9600);

  // check for the presence of the shield:
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue:
    while(true);
  }

  Serial.print("Firmware version: ");
  Serial.println(WiFi.firmwareVersion());
}

void loop() {}

Please Note: The chips are numbered differently but run the same Wi-Fi firmware. You can upgrade the firmware without any worries.


ESP 8266 does not respond at all I have a ESP8266_01, and I wired up. It does not work for me.

I have connected the ESP to an Arduino Uno. I am using a 5V pin from uP with a 3.3V regulator, and I have a voltage divider between RX(ESP) and TX(uP). And I am sure that the wiring is correct. The thing is, I am not getting anything back from ESP, not even errors. And I tried to use different baudrates as well. There is a blue LED flashing from ESP only when I am using 115200, and red LED lights up constantly at any other baudrate.

What have I done wrong here?

I did 4 hours of research already and don't know what else I can do now.
If you have any idea, please leave me a word.

Start by uploading blink sketch to your Arduino then connect it to your ESP8266 like this: TX-TX and RX-RX.

Now open Serial Monitor and send AT command and see if it responds. If so then you can control it using your Arduino by wiring it back to TX-RX and RX-TX.

PS: Don't forget to set the line ending in the Serial Monitor to Newline or Carriage Return.

Edit: Use this code to connect to ESP8266:

#include <SoftwareSerial.h>

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

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

void setup() {
  Serial.begin(115200);
  ESP8266.begin(115200); // Change this to the baudrate used by ESP8266
  delay(1000); // Let the module self-initialize
}

void loop() {
  Serial.println("Sending an AT command...");
  ESP8266.println("AT");
  delay(30);
  while (ESP8266.available()){
     String inData = ESP8266.readStringUntil('\n');
     Serial.println("Got reponse from ESP8266: " + inData);
  }
}

Since the Hardware Serial interface will be busy when connected to Computer, then you have to use another Serial interface to communicate with your ESP8266. In this case, Software Serial comes handy.


How to convert Arduino GSR values to microsiemens? In my project Arduino provides value range between 0-1024. I need to convert this serial value to a standard µSiemens value to measure emotional stress.

Can anybody point me to an answer that would give an appropriate equation for the conversion?

A Siemens (aka a Mho) is a unit of conductance, the inverse of resistance.

You have a measure of the voltage (A/D value) between the pads so you can find voltage. You'll also need to know the current between the pads.
Convert your A/D reading into voltage and use that and the current to find resistance (using Ohm's law), and the reciprocal of the resistance is in Siemens. 1 Siemens == 1,000,000 uSiemens.

https://en.wikipedia.org/wiki/Siemens_(unit)


Error array value after passed to a function I would like to ask about a weirdness in my program. This is my program:

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

void loop() {
   workout_Text();
}

void workout_Text() {
  int woT_x[] = {1, 4, 8, 12, 16};
  int woT_y[] = {1, 4, 8, 12, 16};
  int n = sizeof(woT_y);
  on_led(woT_x, woT_y, n);
}

void on_led(int a_mat[], int b_mat[], int m) {
  for (int i = 0; i < m; i++) {
    Serial.print(a_mat[i]);
    Serial.print(" : ");
    Serial.println(b_mat[i]);
    delay(100);
  }
}

This is the part of my program for a LED matrix. The on_led purpose function is for printing the value of a_mat and b_mat. Instead of printing:

1 : 1
4 : 4
8 : 8
12 : 12
16 : 16
1 : 1
4 : 4
8 : 8
16 : 16

It prints:

1 : 1
4 : 4
8 : 8
12 : 12
16 : 16
13312 : 1
23296 : 4
1 : 8
4 : 12
8 : 16
1 : 1
4 : 4
8 : 8

Where does the big number come from? I am sure that my code is right to just print the a_mat and b_mat.

Thank you.

sizeof counts bytes. the type of your array is int. sizeof of the int array of length 5 is 10 bytes. your for loop goes to i < 10 and reads after the 5th item of the array.


How to read a Text file from server and store to a separate variable? I am working on reading a text file from the server, using http://arduino.cc/en/Reference/GSMClientConnected. It gives me this code:

char path[]="/asciilogo.txt"

I want to store only the contents that are inside the text file to a variable (String). But client.read(); only reads a single character at a time. Also, it takes all the HTTP, GET, TIME parameters together.

How to store only the contents that are present in the text file to a string variable?

Here is what I found:

You need to have a special character like  "*" (a delimiter), from which important data will flow through.

char z = '*';
int s=0;

void setup()
{
  // usual initialization
}

void loop()
{
  if (client.available())
  {
    char c = client.read();
    // Serial.print(c);
    if (z == c)
    {
      s=1;
    }

  if(s == 1)
  {
    int i=0;
    k[i] = c;
    i=i+1;
    // Serial.print(k);
  }

  place +=k;

  Serial.print(place);

  }

.......
}


Serial Monitor not displaying anything I have a very basic script that is supposed to display something to the serial monitor but no matter what I try the serial monitor won't display anything...I;ve watched about 5 tutorials now and each one has failed to display anything. Any ideas what I'm doing wrong?

Here is my code:

char rx_byte;

void setup() {
  Serial.begin(115200);
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);
}

void loop() {
  if(Serial.available() > 0){
    rx_byte = Serial.read();
    Serial.print("You typed: ");
    Serial.println(rx_byte);
    digitalWrite(13, HIGH);
    delay(1000);
    digitalWrite(13, LOW);
  }
}

Which one are you using?
The one closest to the reset button, I believe its the native...

This is more confusing than I realized. The Due has two ports:

Programming port
For programming, the programming port is easiest to use. And you can "talk" to the serial port using Serial, like this:
void setup ()
  {
  Serial.begin (115200);
  Serial.println ("Hello, world!");
  }  // end of setup

void loop ()
  {
  }  // end of loop

Native USB port
This lets you emulate USB devices (eg. keyboard, mice). However if you want to use it for Serial communications you need to use a different class SerialUSB like this:
void setup ()
  {
  SerialUSB.begin(115200);
  while (!SerialUSB) ; // wait for it to become ready
  SerialUSB.println ("Starting ...");
  }  // end of setup

unsigned long i;

void loop ()
  {
  SerialUSB.print ("Hello, world! Count = ");
  SerialUSB.println (++i);
  delay (1000);
  }  // end of loop

It also helps to wait for the serial port to become ready, as I did in setup. Otherwise you may miss the first 10 lines or so of serial output.


Arduino's Serial Monitor Showing Constant Value I have a breadboard Arduino; made with ATMega328PU and a UART connector using a CT2102 breakout board. With the help of this site I created a simple IR sensor, now the problem is that in the Serial Monitor I'm getting a constant value of 1023. Even on removing the receiver (photodiode), the value's starts dropping like a capacitor discharges, and then stabilizes at some value (around 260-300).

When everything was working correctly, the value dropped to a sudden zero on removing the receiver, but now it isn't.

The "robot" was working perfectly and was reading the values correctly, but suddenly, the values dropped; we checked it and the Serial Monitor showed the same values. To check if the connections are working, I removed a wire from the Analog Pin of the Breadboard-Duino, and the values started to drop: like a periodic function.

The following code was used:

int pd=2;                      //Photodiode to digital pin 2
int buzz=13;                   //piezo buzzer to digital pin 13
int senRead=0;                 //Readings from sensor to analog pin 0  or A0
int limit=850 / 4;                 //Threshold range of an obstacle
void setup()
{
  pinMode(pd,OUTPUT);
  pinMode(buzz,OUTPUT);
  digitalWrite(pd,HIGH);       //supply 5 volts to photodiode
  digitalWrite(buzz,LOW);      //set the buzzer in off mode (initial condition)
  Serial.begin(9600);          //setting serial monitor at a default baund rate of 9600
 }
void loop()
{
  int val=analogRead(senRead) / 4;  //variable to store values from the photodiode
  Serial.println(val);          // prints the values from the sensor in serial monitor
  if(val <= limit)              //If obstacle is nearer than the Threshold range
  {
   digitalWrite(buzz,HIGH);     // Buzzer will be in ON state
   delay(20);
  }
  else if(val > limit)          //If obstacle is not in Threshold range
  {
   digitalWrite(buzz,LOW);      //Buzzer will be in OFF state
       delay(20);
  }
}

Any help will be appreciated.

EDIT

The phototransistor/diode is a standard 2pin component which came with the IR sensor.

In your initialisation where you declare each variable and 'connecting' them to a pin you make a mistake. Now you say that senRead is a digital pin instead of a analog pin. Change the value to A0 so you will get

int senRead = A0;

Also in your void Setup() you forget to declare your analog pin as an input. Add a pinMode command that sets senRead as an input.

If this doesn't fix your problem then it is probably hardware related. Check the connections on your breadboard will most of the times solve alot of problems.


How to detect button presses with a 74HC595 shift register? Is there a way I can have my arduino uno differentiate between pushbuttons that are wired through a shift register and detect when each are pressed or not? I found this tutorial for the 74HC165 but I'm not sure it's applicable to the 74HC595.

The 74HC595 is a deserializer while the 74HC165 is a serializer. This means the former consumes a serial datastream and provides all data bits in parallel on dedicated data lines. While the latter consumes parallel data and converts it to a serial datastream.

To scan buttons you want to have parallel input data, where each switch is attached to a single data line. Then you serialize the data to reduce the amount of required Arduino inputs. This method is well explained in the mentioned tutorial.

As the 74HC595 is a deserializer it is not really applicable here. Instead you could use it to drive multiple outputs through a serial interface (see https://www.arduino.cc/en/tutorial/ShiftOut as an example).


Arduino as switch for external circuit I am trying to use the Arduino as a switch for an external circuit.

I first thought about using a shift register, but this wont allow me to switch the external circuit. Here is a little sketch of what I want to do :

So basically I got this external circuit with a 3 position switch. And I want to replace this manual switch with an Arduino so it can be controlled by a PC, without influencing the other circuits Voltage or Amps...

Any suggestions ?

Three-position makes it a little more tricky than normal.

The simplest option, though depending on what the circuit is, maybe not the safest option, is to use three relays.

Switch only one relay on and it is the same as having the three-position switch in that same state. Switch that relay off and switch another on and you have changed the switch position.

The danger is that this arrangement can have two or even three relays on at once, something that can't happen with a switch.  Also how you do the switching could be critical. Switch one relay off, then add a delay before switching the next one on, so that the previous one has a chance to switch off properly first. That way you avoid having two on at once. Of course, depending on what it is you're switching, that may or may not be an issue.

The safest option, though the hardest to create, would be to physically move the existing switch with, say, a servo motor. Without knowing a little more about the mechanics of your switch I can't really advise more on this option.


Arduino Master-Slave Pins Can I change the pins on the communication for a Master-Slave arduino Wire transmission? I want to communicate between 2 arduinos, but on one of them A4&A5 are taken

You cannot. Wire uses hardware I2C, and on the Uno only A4 and A5 are connected to the TWI peripheral on the MCU. You will need to either switch to a bit-bang I2C implementation or change the protocol you're using.


Confusion with two Serial.begin() function calls Why are there two Serial.begin() function calls? What does that signify?
   Here is the minimal code i am working on:

void setup() {
      Serial.begin(115200);
      Serial.begin(9600);
      Serial.println("Pressure Sensor Test"); Serial.println("");
    }

Here is the full Code:

#include <SimpleDHT.h>
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BMP085_U.h>

int pinDHT11 = 2;
Adafruit_BMP085_Unified bmp = Adafruit_BMP085_Unified(10085);

void displaySensorDetails(void)
{
  sensor_t sensor;
  bmp.getSensor(&sensor);
  Serial.println("------------------------");
  Serial.print  ("Sensor:       "); Serial.println(sensor.name);
  Serial.print  ("Driver Ver:   "); Serial.println(sensor.version);
  Serial.print  ("Unique ID:    "); Serial.println(sensor.sensor_id);
  Serial.print  ("Max Value:    "); Serial.print(sensor.max_value); Serial.println(" hPa");
  Serial.print  ("Min Value:    "); Serial.print(sensor.min_value); Serial.println(" hPa");
  Serial.print  ("Resolution:   "); Serial.print(sensor.resolution); Serial.println(" hPa");
  Serial.println("----------SDNx real time scientific data---------------");
  Serial.println("");
  delay(500);
}

void setup() {
  Serial.begin(115200);
  Serial.begin(9600);
  Serial.println("Pressure Sensor Test"); Serial.println("");
  if(!bmp.begin())
  {
    /* There was a problem detecting the BMP085 ... check your connections */
    Serial.print("  Ooops, no BMP085 detected ... Check your circuit some errors are there!");
    while(1);
  }

  /* Display some basic information on this sensor */
  displaySensorDetails();

}

void loop() {

  Serial.println("===========");
  Serial.println("Sample DHT11...");

  byte temperature = 0;
  byte humidity = 0;
  byte data[40] = {0};
  if (simple_dht11_read(pinDHT11, &temperature, &humidity, data)) {
    Serial.print("Read DHT11 failed");
    return;
  }

  Serial.print("Sample RAW Bits: ");
  simple_dht11_serial_print(data);

  Serial.print("SDNx says you are genius and every thing is OK: ");
  Serial.print((int)temperature); Serial.print(" *C, ");
  Serial.print((int)humidity); Serial.println(" %");

  // DHT11 sampling rate is 1HZ.
  delay(1000);

  sensors_event_t event;
  bmp.getEvent(&event);

  if (event.pressure)
  {

    Serial.print("Pressure:    ");
    Serial.print(event.pressure);
    Serial.println(" hPa");

    float temperature;
    bmp.getTemperature(&temperature);
    Serial.print("Temperature: ");
    Serial.print(temperature);
    Serial.println(" C");

    float seaLevelPressure = SENSORS_PRESSURE_SEALEVELHPA;
    Serial.print("Altitude:    ");
    Serial.print(bmp.pressureToAltitude(seaLevelPressure,
                                        event.pressure));
    Serial.println(" m");
    Serial.println("");
  }
  else
  {
    Serial.println("Sensor error");
  }
  delay(1000);
}

It looks like a mistake, as Chris says.  I can't tell you what will happen but my guess is it will work at 9600.

I would recommend that you delete one of the lines to avoid further confusion.


Detect if a display is connected I want to detect wether a display is connected or not.
This is the display: https://www.az-delivery.de/en/products/1-77-zoll-spi-tft-display
I read connecting a pin of the display with another pin with a pull up resistors. Unfortunetely nothing worked so far.
My microcontroller board is Arduino Mega.

As jsotola mentioned in his comment, pin 1 and pin 14 on the display are connected to each other (GND). You can connect pin 14 to an input pin with enabled INPUT_PULLUP. If no display is connected, this pin will be pulled high by the pullup, thus the pin will read high. If the display is connected, the pin will read low.


Using Sleep AND LowPower.h I am trying to set up the low power module for an instance case,
I have installed the low power library but when I am using the
line

LowPower.powerDown (SlEEP_5S, ADC_OFF, BOD_OFF) ;

It is throwing an error stating that the 'SLEEP' was not declared in the scope.
Any suggestion for that ? Do I have to include a library for sleep too ?

#include "LowPower.h"
  /// DON' t worry about the setup and loop, i have defined all those.

This set of code is in

  void Loop()
    ...
    else
    {
       LowPower.powerDown (SLEEP_10S, ADC_OFF, BOD_OFF) ;

There is no 5 or 10 second sleep. You can't just arbitrarily choose how long to sleep for. The watchdog timer only has specific periods (defined by dividing the clock by a set amount) that it can sleep for:

enum period_t
{
    SLEEP_15MS,
    SLEEP_30MS,
    SLEEP_60MS,
    SLEEP_120MS,
    SLEEP_250MS,
    SLEEP_500MS,
    SLEEP_1S,
    SLEEP_2S,
    SLEEP_4S,
    SLEEP_8S,
    SLEEP_FOREVER
};

To sleep for 5 seconds you would need to sleep first for 4 seconds, then wake up, and then sleep for a further 1 second after that. For 10 seconds sleep for 8 seconds followed by 2 seconds.

Note that they aren't exact values, however, since the watchdog oscillator is very crude and varies wildly in frequency with both temperature and power supply voltage.


How to test Arduino board? A little history: I have two Arduino Uno and I couldn't program them by IDE, I got these errors:

avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00

So I googled it for a while and I suspect of missing bootloader on atmega micro on the board, as I don't have AVR programmer I programmed both Arduinos with Raspberry Pi and Arduino IDE tool through ICSP pins.

It (burning bootloader) runs perfectly on both Arduino. One of them got fixed and got back to normal, but the other one gave me same error, so I changed their Atmega micro, but same result. Second Arduino (bad one) can't transfer program to AVR even with other one (good one) AVR so both AVRs on the boards are good.
The program (blink LED) run even on the bad Arduino and pin 13 blink.

My questions are:

How could I test the suspected Arduino board? Is the second Atmel micro near usb female port need bootloader too?

  Update 1: I follow this tutorial but my Arduino couldn't go to DFU
  mod by shorting the pins. When I connect those pins led pin 13 not blink and lsusb command show Arduino not Atmel.

  Update 2 : I went through this question and this
  troubleshoot to upload bootloader to Atmel USB device but my
  second Arduino (bad one) didn't respond and gave me this error :

Atmega chip detector.
Written by Nick Gammon.
Version 1.17
Compiled on Jul 13 2015 at 11:14:35 with Arduino IDE 105.
Attempting to enter ICSP programming mode......................................................
Failed to enter programming mode. Double-check wiring!
Programming mode off.

  Is it possible my Atmega16U2 chip is burned?

  Update 3 : I do reach the point that I am pretty sure Atmega16U2 is
  dead and it isn't responding to its ICSP pins and it blocks any USB to AVR connection. I check the wiring and I
  test it on good Arduino and its sequence are correct and it works on good one. Now what can I
  do, as Atmega16U2 is not rechangeable, should I throw bad Arduino away?

does the built-in arduino LED light up?? If yes try connecting your arduino in another uno usb port or try pressing the reset button on your arduino uno.


Multiplying the voltage output I'm working on a project where my arduino is receiving a voltage 0-5V, I need the output to be 10V always. Is there a way to do that?

Assuming the 0-5 Volts is supposed to switch the output, in which case you want a program to control your output, then you will want to use a digital output pin to either switch a relay or a transistor that controls the 10 Volts put out to whatever it is that you are controlling.

Perhaps you want PWM which indicates a transistor circuit.  Hard to tell what you want from the way this is worded.

Taking your words literaly, "I need the output to be 10V always" then that simply means hard-wiring to a 10V power supply.   ;-)


Flashing dotStar LED I have a DotStar LED strip that I want to make it blink (e.g., 1 second on, 5 second off in an endless loop).

I tried doing so via the script below but it does not work. Can someone please explain me how to do so?

Script:

#include <Adafruit_DotStar.h>
#include <SPI.h>

#define NUMPIXELS 10

#define DATAPIN    4
#define CLOCKPIN   5
Adafruit_DotStar strip = Adafruit_DotStar(NUMPIXELS, DATAPIN, CLOCKPIN, DOTSTAR_BRG);

void setup()
{
  strip.begin();
  strip.show();
}

void loop()
{
  strip.show();
  strip.setBrightness(155);
  for (int i=0; i <= 10; i=i+1) {
    strip.setPixelColor(i, 255, 255, 255);
  }
  delay(1000);

  strip.setBrightness(0);
  delay(5000);
}

The authors of the library are not fans of the setBrightness() method and advise handling it yourself.

The following code should do what you want.

#include <Adafruit_DotStar.h>
#include <SPI.h>

#define NUMPIXELS 60 // This should be the total number of LEDs in your strip

#define DATAPIN    4
#define CLOCKPIN   5
Adafruit_DotStar strip = Adafruit_DotStar(NUMPIXELS, DATAPIN, CLOCKPIN, DOTSTAR_BRG);

void setup()
{
  strip.begin();
  strip.show();
}

void loop()
{

  // loop through each pixel in the control array setting it to the colour mix you want.
  for (int i=0; i <= NUMPIXELS; i=i+1) {
    strip.setPixelColor(i, 25, 25, 25); // Even 25 on my strip gives reasonably bright flash
  }

  strip.show(); // Then push the control array to the strip
  delay(1000); // and leave it set for a while

// Then do it again for the 2nd brightness in your scheme

  // loop through each pixel in the control array setting it to off.
  for (int i=0; i <= NUMPIXELS; i=i+1) {
    strip.setPixelColor(i, 0, 0, 0);
  }

  strip.show(); // Then push the control array to the strip
  delay(1000); // and leave it set for a while

}


Making two Arduinos/MKR1000 communicate I am trying to create a project in my free time just for a bit of fun -
it consists of two MKR1000 (one acting as a web server connected to one laptop, and the other acting as a web client connected to a different laptop - so I can view the Serial Monitor).

One MKR1000 has a potentiometer attached to it (therefore I can change the value of it), and sends the potentiometer value to the serial monitor every 4 seconds.

THE AIM: Once the web server sets up the wifi network, and the web client connects to that wifi network, I want to send the potentiometer value across to the web client every time it gets updated. However I am clueless on how to achieve this.

This is my web server void loop code (the rest is similar to the https://www.arduino.cc/en/Tutorial/Wifi101WiFiWebServer):

void loop() {
  WiFiClient client = server.available();
  // listen for incoming clients
  if (client) {
    // if you get a client,
    Serial.println("new client");
    // print a message out the serial port
    String currentLine = "";
    // make a String to hold incoming data from the client
    while (client.connected()) {
      // loop while the client's connected
      if (client.available()) {
        // if there's bytes to read from the client,
        char c = client.read();
        // read a byte, then
        Serial.write(c);
        // print it out the serial monitor
        if (c == '\n') {
          if (currentLine.length() == 0) {
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println();
            // the content of the HTTP response follows the header:
            client.print("Click here showValue of the potentiometer
");
            // The HTTP response ends with another blank line:
            client.println();
            // break out of the while loop:
            break;
          } else {
            // if you got a newline, then clear currentLine:
            currentLine = "";
          }
        } else if (c != '\r') {
          currentLine += c;
          // add it to the end of the currentLine
        }
        if (currentLine.endsWith("GET /showValue")) {
          Serial.println(sensorValue);
          delay(2000);
        }
      }
    }
    client.stop();
  }
}

And this is my web client code I use this https://www.arduino.cc/en/Tutorial/Wifi101WiFiWebClient  - I am not sure how I should modify this in order to receive the potentiometer value across from the web server MKR1000. Any tips or hints would be hugely appreciated!

I am sorry if this is a simple question, however I am just starting with the Arduino idea, and I'm new to coding!

Thanks.

At the bottom of the page for the client code link you provided, there's a link to a Chat Server example. If you study the code I think you'll see how to send and receive the potentiometer reading. Hint: Look in the code where it echoes what it receives.

mkr1000 WiFi Chat Server


How to detect when intercom is ringing? For my apartment, I need to check when intercom is ringing and call an API in that case. I was thinking about using an AC input / DC output relay, since the buzzer signal is an AC signal. Is there an equivalent pre-built component similar to this?

As it sounds like you do not own the buzzer (it is part of the appartment), someone may not like you directly connecting to it.

If this is a classic buzzer with an electromagnet, consider using a Hall Effect Sensor.  The magnetic field generated by the buzzer may be able to activate the Hall Effect Sensor and inform the Arduino the buzzer has been activated.  This article talks about Hall Effect sensors and an Arduino.

Image of Arduino and Hall Effect Sensor from linked to article:

Further, this is a much safer way connect to a buzzer.  As a classic buzzer can generate very high voltages that can damage processors and other sensitive electronic devices when directly connected.


Need a proper diagram to connect my multiple relays (more than 8) with only a few pins on Arduino Uno Board Specifically, I want to add multiple relays (approximately 36 to 40) to an Arduino Uno board (using only a few pins). I found a solution using ShiftOut. You can take a look here. But here the example is for testing small LEDs bulbs.

I will control high-voltage electricity like fans, tube lights, washing machine with those relays, so what will be a proper graph or image diagram for that? And if you have any more suggestions for me then you can tell me :) And yes please tell me what I should use for it.

Right now am thinking to use an Arduino, relays, 74HC595 IC only. My diagram for controlling LED is like this:

You can edit it. I just need proper guidance for it and a few good suggestions.

If you want to drive a normal magnetic relay you will need to add a transistor / resistor to the output of the 74HC595 as the current is too high across the magnet of the relay to be driven directly by the 74HC595. If you don't want to use a transistor for every relay, you could you an 8 channel driver chip like the ULN2803A. You should be able to connect your relay coil directly from 12v and to the ULN2803A.

Have a look at this page for an example. http://www.mcmajan.com/mcmajanwpr/blog/2014/04/18/arduino-how-to-connect-many-12v-relays-en/


How to connect a MPU-6050 to an Arduino that already has a CNC Shield V3 on top of it? I have a CNC Shield on top of an Arduino Uno (GRBL pinout) that controls 2 stepper motors through a4988 drivers and it is working like a charm.

Now I want to add an accelerometer to it. From my humble research, the MPU-6050 seems a good pick.

If I purchase stacking headers to lift the CNC shield, can I connect the accelerometer to the unused/reserved A4 and A5 from the Arduino, but power it using CNC's Ground and 5V pins?

I'm open to other approaches if I'm not doing it the proper way.

MPU6050 can use only I2C. Those are pins A4 and A5 on an Uno. 5V and ground are 5v and ground, no matter from which pin


Best way to measure liquid level of a 10 meter high tank? I would like to measure the height at which the liquid inside a 10 meter high tank, what is the best way to achieve it?

What sensor should i use? I have seen ultrasound sensors but I have not found one that covers 10 meters. In context, I need to measure the volume of the liquid.

I don't know whether to measure the distance between the bottom and the height of the liquid, or measure the vacuum.

Example: If a 10 meter tank has 4 meters of liquid, you could calculate its volume by:

1) The maximum height at which the liquid reaches from the bottom to the top. Thus, it is estimated that from the bottom to the top there are 4 meters of liquid.

2) The distance at which the mouth of the tank touches the water. Thus, it is estimated that the tank is empty 6 meters and the rest is liquid. Could you instruct me a little? Thank you.

Edit: I add that the tank is fuel and that my budget does not exceed $ 20. Besides that I can not make modifications to the tank at my whim. Currently, to measure the height, a measuring tape attached to a lead is used so that it falls to the bottom of the tank, when the measuring tape is raised, the height at which the liquid wets the tape is seen. Hence the fuel level is obtained.

I don't know what is the “best”, and in fact I would be interested in
knowing the answer. So far the best option I found seems to be a
submersible level sensor (do a Web search for these words). These are
pressure sensors that you put at or near the bottom of the tank. They
give you a reading proportional to the height of water above the level
of the sensor.

Most of these sensors seems to give an output in the form of a
4 – 20 mA current. They are have only two wires and
expect a supply somewhere in the range of 24 V. You will then need
a suitable supply and some electronics to convert that to an analog
voltage that your Arduino can read. A simple resistor would be enough
but you probably want something that provides some safety in case the
sensor fails short. You can search this site for "4-20 mA", as the topic
of interfacing these kind of sensors has already been covered here
multiple times.


Why do all analog pins measure the same value? I measure 2 analog pins: A4 and A5. The A5 pin is connected to another Arduino's digital out (through a 10k resistor) which has a simple program: 5ms on and 100ms off. The A4 pin is not connected anywhere.

The analog pins are inited with pinMode(APIN, INPUT), reading is simply performed with the analogRead(APIN) function (there is no delay between the readings). I have tried with delays between the measurements but the results are the same.

The results:

The A5 pin (which is connected) measures the correct value. However, the unconnected A4 pin is clearly interferred by the input of A5. It works like this with another pins, delays between the readings, double use of analogRead()... I even swapped the Arduinos (Arduino Nano and Uno) and the results are the same.

Is it because of that these Arduinos are clones? Or are these Arduinos damaged?

If you want to measure a pin (i.e. defined as input pin, either digital or analog), you have to use a pull up or pull down resistor (either internal or external depending on what the MCU GPIOs have).

This resistor makes sure in case there is nothing attached, that the (mostly high ohm) resistor will make sure the nonconnected pin will either give a LOW or HIGH as input (or in case of analog, the minimum or maximum value).

When the pin is connected, the pull down/up resistor will change the result so marginally that it can be ignored.


Stop led from blinking when running I don't get it. I'm new to Arduino, but not to programming. I don't understand why led pin 13 keeps blinking.

here is my code..

#include <Servo.h>

// X servo angle will stay in [min_x, max_x] range
// Y servo angle will stay in [min_y, max_y] range
// to be adjusted to the size of your living room

float min_x = 5;
float max_x = 50;
float min_y = 5;
float max_y = 35;
int min_freeze = 200;
int max_freeze = 3000;
float minimal_movement = 5;

// finding center of square for starting point
int random_delay;
float x_position = min_x + (max_x - min_x)/2;
float y_position = min_y + (max_y - min_y)/2;
float x_old_position = x_position;
float y_old_position = y_position;
float x_new_position;
float y_new_position;
float x_speed;
float y_speed;
int movement_time;

// Instantiating two servos
Servo x_servo;
Servo y_servo;
int pos = 0;

void setup() {
  y_servo.attach(6);  // attaches the y servo on pin 6 to the servo object
  x_servo.attach(9);  // attaches the x servo on pin 9 to the servo object
  pinMode (13, OUTPUT);
  digitalWrite (13, HIGH);  // switch on  the laser

  //Place the servos in the center at the beginning
  y_servo.write(y_position);
  x_servo.write(x_position);

}

void loop() {
  movement_time = random(10,40);
  random_delay = random(min_freeze, max_freeze);
  x_new_position = random(min_x+minimal_movement, max_x-minimal_movement);
  y_new_position = random(min_y+minimal_movement, max_y-minimal_movement);

  if( (y_new_position > y_old_position) && (abs(y_new_position - y_old_position) < 5 )) {
    y_new_position = y_new_position + minimal_movement;
  }  else if ( (y_new_position < y_old_position) && (abs(y_new_position - y_old_position) < 5 )) {
    y_new_position = y_new_position - minimal_movement;
  }

  if( (x_new_position > x_old_position) && (abs(x_new_position - x_old_position) < 5 )) {
    x_new_position = x_new_position + minimal_movement;
  }  else if ( (x_new_position < x_old_position) && (abs(x_new_position - x_old_position) < 5 )) {
    x_new_position = x_new_position - minimal_movement;
  }

  x_speed = (x_new_position - x_old_position)/movement_time;
  y_speed = (y_new_position - y_old_position)/movement_time;
  for (pos = 0; pos < movement_time; pos += 1) {
      x_position = x_position + x_speed;
      y_position = y_position + y_speed;
      x_servo.write(x_position);
      y_servo.write(y_position);
    delay(10);
  }
  x_old_position = x_new_position;
  y_old_position = y_new_position;
  delay(random_delay);

}

Nowhere in this sketch, the line "digitalWrite (13, LOW);" is contained, yet I am unable to keep the LED on solid without blinking when the Arduino is looping. I've other people do it, with this code, I don't get what I'm missing!

Windows 7 64bit, Arduino Uno board, Arduino 1.8.9 program

I tried your sketch on an Arduino Uno, with no servos connected, and the LED on pin 13 did not blink.

DataFiddler makes a good point in their comment. To be sure you are actually uploading the sketch, try uploading the Blink sketch that comes with the IDE. Change the delays from 1000ms to 200ms then upload it. The difference in flash rates should confirm or deny the ability to successful upload sketches.

You don't say which servos you are using, so I'll assume they are SG90. I'm not sure if the data sheet for every SG90 servo is the same, but if you look at this one, SG90 Specifications, you'll see the "stall current" can be between 570mA and 730mA, each. If you are powering them from the Uno, it can't supply that much current. Another limiting factor is the computer's USB maximum current output, (if you are powering the Uno with a USB port). FWIW, my computer can only provide 500mA per USB.

I would suggest powering the servos with a separate power supply, then see what happens.


EFCom GPRS/GSM Shield I have an EFCom GPRS/GSM Shield
http://www.elecfreaks.com/wiki/index.php?title=EFCom_GPRS/GSM_Shield
and I am using it with a mega 2560. The problem is that the code in the wiki page

//Serial Relay - Arduino will patch a
//serial link between the computer and the GPRS Shield
//at 19200 bps 8-N-1
//Computer is connected to Hardware UART
//GPRS Shield is connected to the Software UART

#include <SoftwareSerial.h>
SoftwareSerial mySerial(2, 3);
void setup() {
  mySerial.begin(19200);               // the GPRS baud rate
  Serial.begin(19200);                 // the GPRS baud rate
}

void loop() {
  if (mySerial.available())
    Serial.write(mySerial.read());
  if (Serial.available())
    mySerial.write(Serial.read());
}

makes use of software serial but mega 2560 cannot use software serial on pin 2, as in the arduino reference, thus I changed the pins to 50 and 51 and used external female-male headers to connect s_tx to pin 50 "rx" , and s_rx to pin 51 "tx", still no response with the AT command...

code after update is :

#include <SoftwareSerial.h>
SoftwareSerial mySerial(50, 51);
void setup() {
  mySerial.begin(19200);               // the GPRS baud rate
  Serial.begin(19200);                 // the GPRS baud rate
}

void loop() {
  if (mySerial.available())
    Serial.write(mySerial.read());
  if (Serial.available())
    mySerial.write(Serial.read());
}

Note that I am using the Arduino IDE serial monitor.

Try to connect "Pin RX on Mega to Pin RX on Shield" an "Pin TX on Mega to Pin TX on Shield":

Pin 50 (Rx)  on Mega <==> Pin 2 GSM Rx on Shield
Pin 51 (Tx)  on Mega <==> Pin 3 GSM Tx on Shield

I use an Geeetech Shield with a Mega 2560 and connect RX to Rx and TX to TX. Works fine.

Another solution is to use Serial1 instead of using SoftwareSerial ...

First connect:

Pin 19 (Rx1)  on Mega <==> Pin 2 GSM Rx on Shield
Pin 18 (Tx1)  on
Mega <==> Pin 3 GSM Tx on Shield

    //Serial Relay
    unsigned char buffer[64];  // buffer array for data receive over serial port
    int count=0;               // counter for buffer array

void setup()
{
  Serial1.begin(19200);
  Serial.begin(19200);
}

void loop()
{
  if (Serial1.available())
  {
    while(Serial1.available())
    {
      buffer[count++]=Serial1.read();
      if(count == 64)break;
    }
    Serial.write(buffer,count);
    clearBufferArray();
    count = 0;
  }
  if (Serial.available())
    Serial1.write(Serial.read());
}

void clearBufferArray()
{
  for (int i=0; i<count;i++)
  {
    buffer[i]=NULL;
  }
}

You can use a Arduino IDE's Serial Monitor, Serial Terminals(sscom32) or Bray++ Terminal to send AT commands to the Shield, communicate with it.

I hope this information is helpful.


Arduino shield stacking I have an Arduino GSM Shield mounted on an Arduino Uno. Can I stack this GPS shield above Arduino GSM shield? Will there be any pin configuration problem?

In GSM Shield hardware pin’s configuraton are as below:

0 - Not connected
1 - Not connected
2 - GSM Rx
3 - GSM Tx
7 - Modem reset

If there is any problem, how can it be solved? I would be happy if there are any alternatives for the GPS shield.

Addendum

The schematic of the Arduino GSM shield:

The schematic of the SparkFun GPS shield:

Photo by John Boxall

Which pins do they use?

To determine if two shields are compatible, you have to read the specifications of both shields.

The best source for this information is the data sheets supplied with the shields. However there is also this Shield List

Can you reassign pins?

Some shields provide a means to alter which pins are used for communications. This can take the form of a switch or a jumper - either pull-off or solder-bridge type. (the GPS shield in the question has jumpers).

Where the shields do not support pin-reassignment or provides insufficient flexibility, to work-around incompatibilities you can use an in-between shield designed for the purpose.

here is one example:

  You hear it all the time in the Arduino community, “will this shield work with my other shield?.” I think we’ve all been disappointed to find that two of our favorite shields compete for control of a digital pin here or a serial pin there. While there are sometimes some clever workarounds from elegant code modifications to aggressive ‘greenwiring,’ Mayhew Labs may have come up with the simplest solution thus far: The Go-Between Shield.

Are any alternatives for the foo shield

I notice that Arduino.cc now point people to the list referenced above. They used to have their own list.

Product recommendations are off-topic here but, obviously, you can search


How to get Transmission package Timestamp from ESP8266 I am trying to make an Indoor positioning system using ESP8266 as a beacon, how do I get the transmission package timestamp from router to ESP8266 and vice-versa?

Thank you in advance for any advice

You can use timestamp from NTP client and attach it

Install NTPclient library from Arduino library manager
This library uses WiFiUdp library to connect to the NTP server, so download that too

Then you can just update the time every time your sending/receiving something and log it as and how you see fit!


Beginner Arduino Project: Drumming Robot So, I've got a music degree, 5 years programming with Ruby and 7 with Pure Data. I've also got hold of an Arduino and a Raspberry Pi.

Anyway, I've seen a number of Arduino projects which involve firing events which cause a stick to hit a drum, but I really don't know where to start.

I have a wicker penguin that I want to have play the drums:

What components do I need to produce this kind of one-off percussive event?
Can I trigger these events from Ruby?

The approach I would take for the arms is to use a servo motor as these are fairly cheap and are closed loop so you don't have to add any extra sensors to check where the current position is.

Types of Motors:

Stepper motors are a type of motor with a special arrangement of coils that allows you to turn a fraction of a degree by sending pulses to the motor. For example, you can buy a 200 step stepper motor that turns in increments of 1.8 degrees. These are somewhat expensive and require somewhat expensive drivers (usually $5-10 per driver). Often used in CNC machines and 3D printers. Continuous rotation.
General DC motors (two types: brushless and brushed, but I won't get into that in here) are a type of motor. Their drivers are often cheaper than one for a stepper motor, but you have little control over their rotation (instead of "take one step which is X degrees," you say , "turn at 25% power clockwise," where you don't know the actual speed). These are sometimes used with rotary encoders or potentiometers to control the speed and position of the spindle. Continuous rotation.
Servo motors are actually not their own type of motors; they are DC motors (not steppers) with a potentiometer built in along with the driver. You send pulses to it (you can use the Arduino servo library for this) to tell it the exact degree to go to. Can only go a limited range: usually either 90 or 180 degree, although you can get special ones that can turn much longer ranges than that.

Using a Servo Motor:

You can hook it up like this:

  From this Arduino Tutorial

And then some very simple code to use the motor:

#include <Servo.h>

Servo myservo;

void setup() {
  myservo.attach(9);
}

void loop() {
  myservo.write(10);
  delay(500);
  myservo.write(0);
  delay(500);
}

Talking with Ruby:

Your best option is to use the serial port on your computer. Figure out how to access a COM/serial port in Ruby. You can then send messages from your computer to the Arduino, but you'll have to figure out a way to structure the messages.


How to make 12V flashing LEDs using an Arduino Uno? I have 3 LEDs powered by an Arduino; each LED has its own flash rate.

Now I want it to be powered by an external 12V power source and still have the flashing function of the Arduino?

Use a N-channel MOSFET, wire load to drain pin, source to (common) ground, and place a 1 kilo-ohm resistor in series with your arduino pins. Bear in mind that MOSFETs respond to voltage, not milliamps, on the gate - get one that responds well to 5V logic.


Arduino serial hex decimal values code I'm trying to send heximal values from arduino to PZEM-04 power module (it shows voltage, current and ect.) over serial communication in heximal format and get values in decimal format for further actions with them. Any help with the code please?
One of the commands:
Send command: B4 C0 A8 01 01 00 1E
Reply data: A4 00 00 00 00 00 A4

Edit: I am connecting wires from PZEM module TTL to arduino "serial port": TX-RX, RX-TX, VCC-VCC, GND-GND, so it's serial communication..
    PZEM module: http://www.aliexpress.com/store/product/PEACEFAIR-AC-100A-Electric-power-monitoring-and-communication-module-power-meter-power-energy-Volt-Ammeter/1773456_32373508101.html

A possible implementation of the protocol using serial read/write of binary data (command and response).

void send(Stream& ios, uint8_t cmd[6])
{
  uint8_t sum = 0;
  for (int i = 0; i < 6; i++) {
    uint8_t c = cmd[i];
    sum += c;
    ios.print((char) c);
  }
  ios.print((char) sum);
}

bool recv(Stream& ios, uint8_t res[6])
{
  uint8_t sum = 0;
  uint8_t c;
  for (int i = 0; i < 6; i++) {
    while (!ios.available());
    c = ios.read();
    sum += c;
    res[i] = c;
  }
  while (!ios.available());
  c = ios.read();
  return (sum == c);
}

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

  uint8_t cmd[] = { 0xB4, 0xC0, 0xA8, 0x01, 0x01, 0x00 };
  uint8_t res[6];
  send(Serial, cmd);
  recv(Serial, res);
}

void loop()
{
}

Cheers!


could not convert 'digitalWrite(8u, 1u)' from 'void' to 'bool' I am trying to make some LED lights to turn on when i flick a switch on my RC crontroller. I will connect the signal wire from RC controller to pin 8. The plan is: if i flick the swich, the LED's (pin 12,11,10,9) will turn on, and if i don't flick the swich the LED's wont turn on. This is a Arduino nano what will be connected on a drone.I found another question HERE, but there was no real answers.
 I get a error that say:

  exit status 1
  could not convert 'digitalWrite(8u, 1u)' from 'void' to 'bool'

How can i fix this? Should i write the code another way?

Arduino Code:

    void setup() {

  pinMode(4, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(8, INPUT);

}

void loop() {

  if (digitalWrite(8, HIGH));
    digitalWrite(12, HIGH);
    digitalWrite(11, HIGH);
    digitalWrite(10, HIGH);
    digitalWrite(9, HIGH);
  else
    digitalWrite(12, LOW);
    digitalWrite(11, LOW);
    digitalWrite(10, LOW);
    digitalWrite(9, LOW);

  digitalWrite(4,HIGH);
  delay(1500);
  digitalWrite(4,LOW);
}

This line of code is the source of your problem.

void loop() {

  if (digitalWrite(8, HIGH));

If expressions expect a boolean (true/false), but if you check the documentation for digitalWrite(), you’ll see it returns “Nothing” (i.e. void).

You need to use digitalRead() to check the current state of the pin.


servo.read() starts at negative value, no matter where servo actually is I don't like how my servo quickly jumps to the default middle position, so I commented out the line where DEFAULT_PULSE_WIDTH is set in Servo.cpp:

//servos[this->servoIndex].ticks = usToTicks(DEFAULT_PULSE_WIDTH);

Unfortunately while this stopped the servo from moving on execution of attach, the position of the servo is now showing up as -52!

Just running the following in setup() is enough to generate the bug:

int servo_pin = 53;
servo.attach(servo_pin);
Serial.print("Initial position: ");
Serial.println(servo.read());  //returns -52

This last line returns -52 no matter what position the servo is actually in, which has bad consequences (its initial movement is way off).

Note I get the same behavior when I set the DEFAULT_PULSE_WIDTH to 0 in Servo.h.

I am using a Mega -- an Elegoo clone -- on Windows 10.

Note I got the ideas for stopping the servo from moving on initialization from these threads:

https://stackoverflow.com/questions/40892922/how-to-stop-an-arduino-servo-from-moving-during-the-myservo-attach-command?noredirect=1&lq=1
https://stackoverflow.com/questions/26695670/attach-arduino-servo-without-moving

You seem to be starting from a fundamental misunderstanding of RC hobby type PWM servos.  To put it simply, they do not electronically output any position information.

Until you have commanded a position and the servo loop has had a fair chance to seek to that, the position of the servo is utterly and entirely unknowable.

This is stated in the documentation of the Arduino servo system:

read()

Description

Read the current angle of the servo (the value passed to the last call to write()).

As this explains, the returned value is not the physical position, but rather the last commanded position.

Until you have commanded a position (something your code does not do) the return value of this call is physically meaningless.


How can I split a string into three parts after space and turn the values to doubles? I am currently gathering info from a BLE device. I made a thread earlier where I successfully split a string consisting of 5 letters to their unique chars.

However from this BLE device i will also send some different information from time to time where I send 3 different values with a space after each one. So for example looking like this:

-0.1 0.51 0.07

So what I want to do now is to store this three numbers in different doubles and what I have done so far is this:

First i store the recieved message:

String recievedMessage;

recievedMessage += (char)BTLEserial.read();

Now I have to determine if the value sent is the 5 letters or if it is the numbers with a space between each value.

if (recievedMessage.length() > 5) //so if the recievedmessage is more than 5 words then it is the 3 values that is being sent.
{
char * charTheMessage = recievedMessage.c_str();
char *str;
str = strtok(charTheMessage, " ");

double one = str[0];
double two = str[1];
double three = str[2];

Serial.println (one);
Serial.println (two);
Serial.println (three);

}

if (recievedMessage.length() == 5)
{
 //http://arduino.stackexchange.com/questions/36227/how-can-i-split-a-string-into-multiple-parts/36237?noredirect=1#comment72313_36237
//Here I split the letters into 5 different values if the value sent is 5.
}

But this values do not come out right when I print them in the serial monitor. I have also read that strtok is not reliable when data is sent fast so is strtok the right way to go you think?

You're almost there. Strtok returns the first token in the string only. You then have to convert that to a double yourself. You then call strtok again with NULL as the source string to get the next token. And so on.

I have written a good strtok example on here already. Look around, you may find it.


Is it possible to print client IP or MAC address from Arduino WiFi web server? For a school project I want to make a little project with the Arduino Uno. I want to make a project that does something when a client connects to the WiFi shield.

My first thought was to print out the IP address or MAC address of the client but I can't find the codes for it. It is possible for me to print out the host IP? I have searched on the web for some time but only the ethernet shield will appear. Is my question even possible with an WiFi shield or do I have to get an ethernet shield?

Kind regards.

***** Assuming it is an ESP8266 based WI-FI shield: *****

Wifi shield > PC

Open serial monitor. Baud rate 155200. Also check COM ports.

Test AT commands by typing AT.

If it responds OK, you're good.

Type AT+CIFSR for IP adress.

Full list of AT commands in this link:

http://www.pridopia.co.uk/pi-doc/ESP8266ATCommandsSet.pdf


Multiple power supply for arduino controlled dc motor I’m working on a project where I want to control a motorized fader with an arduino.  I have a dual H-Bridge board to control the motor, but the thing is that it is a 10V motor.  I’m thinking of using a secondary power supply on the H-Bridge to power the motor with a proper voltage.
So here is where my lack of electrical knowledge comes into play.  My H-Bridge has the following connections: a set of +/- poles to provide the power to the motors, 4 motor control pins (2 per motor to control their direction) and 4 motor power pins (2 per motor).

If I was using the Arduino as the power source for the DC motor, I would connect the +5v rail to the + terminal ot the H-Bridge and the Gnd rail to the - terminal, which would, in turn act as the ground return for the control pins.

If I am to use an external power supply, how do I wire it properly so I don’t blowup the arduino or the h-bridge?  I’m guessing that my secondary power supply will be connected to the +/- poles of the H-Bridge and the the - pole will also get connected to the Gnd rail of the arduino?

Is that correct?

According to the datasheet on the L298 IC the connections you described should be right. First I would recommend to connect 10v to the + and - rails and measure the voltage on the logical inputs if it is 0 or lower than 3v than that should be ok to connect an arduino. Also now you can connect an additional 5v power supply with an the -5v connected to the - rail on the board and try to connect the +5v volts to the inputs and measure the voltages on the output (or connect an motor) if everything is ok you can try to connect your Arduino.


For Arduino Uno it is possible to use the digital pins with PWM to read analog data, is this also possible with the Wemos D1 Mini? I want to read out data from a load cell, for this I seem to need 2 analog input pins, the Wemos doesn't have this. In the Arduino I was also able to use the digital pint with PWM, there are also Wemos pins who have that. Is it possible to use them to read the data from the load cell?

There is one way you could measure analogue voltages using a PWM output: Use it as a DAC to build your own Successive Approximation ADC:

The PWM is filtered through a low-pass filter to create an analogue voltage
That is compared to an incoming voltage using a comparator
The output of the comparator is recorded for different reference voltages using a "divide and conquer" method.

You can read more about how Successive Approximation works here.

However, doing that would be overly complex and needlessly expensive. It is far better to just add an ADC chip using I2C or SPI. It's cheaper, easier, and the results will be far superior.

But as a learning exercise to discover how ADCs work, it could be kind of fun.


Adafruit Micro-SD breakout not initializing on MEGA 2560 ]
[I am having quite a bit of trouble trying to get my Arduino MEGA 2560 to read my micro-SD card. My wiring is as follows:

Breakout    Arduino
5v            5v
Gnd           Gnd
CLK           52
DO            50
DI            51
CS            53
CD            Was not connected and then connected to 47 (neither worked)

Here is my code:

#include <Wire.h> //library necessary to use I2C communications bus
#include <Adafruit_Sensor.h>
#include <Adafruit_BME680.h>
#include <SD.h>
#include <SPI.h>

const uint8_t chipSelect = 53; //chipSelect pin for the SD card Reader
const uint8_t cardDetect = 47;

File CO2Data; //Data object you will write your sensor data to

void setup() {
Serial.begin(115200);//"begins" the serial monitor so you can print stuff out when connected to the computer (set baud rate to 115200)
Wire.begin ();//begins the I2C communications bus so it can talk to the K33

Serial.print("Initializing SD car...");
pinMode(53, OUTPUT);

if (!SD.begin(chipSelect)) {
Serial.println("Card failed, or not present");
// don't do anything more:
while (1) ;
}
Serial.println("card initialized.");
File CO2data = SD.open("datalog.txt", FILE_WRITE);
if (! CO2data) {
Serial.println("error opening datalog.txt");
// Wait forever since we cant write data
 while (1) ;
}}

The SD card is formatted to FAT32.

Thank you for any help!

The non-analog ground line attached to the micro-SD was pulling down my voltage. Just hardwired to different ground and problem solved! (Check your voltages).
From what I could gather. the ground pin on the MEGA inline with the digital pins was a different ground source (digital ground). I literally took the ground lead from the SD board and just touched it to the housing of the USB connector on the MEGA and my voltage came back.


Arduino - Windows can't find the drivers I bought an Arduino UNO R3 Yesterday. It's a Chinese clone. But it has the Atmega328p and MEGA16U2 both.
I've installed the IDE fully. But it can't find the ports. The Tools > Ports option is greyd out, Cannot find The options Named "Ports (COM & LPT)" or "Other Devices" in device manager. Can't upload any sketch to board.
I tried this on my both Win7 SP1(32 BIT) & Win10, which are installed in the same pc but in different partitions. I've roamed accross stackexchange but no successful result.

You may not have installed the drivers when installing the IDE. The only way I know to reinstall the drivers is to reinstall the IDE and make sure when you get to this screen you tick every box:

Otherwise you may not have selected your board correctly. To select your board in the IDE, go to Tools > Board > Arduino Uno/Genuino Uno

Your port select may then appear, it should be COM1 or something similar. If you have multiple, just try them all by selecting one and then upload a sketch to it. The Arduino Uno should flash some lights if it worked correctly.


"Hello World" program for nRF24L01+? Where is a simple program that demonstrates unidirectional data transmission over a pair of nRF24L01+ radios?  It should have adequate output so that a beginner can determine that the transmission is working properly.

Here are several "getting started" articles that contain simple programs.

http://tmrh20.github.io/RF24

https://groups.google.com/forum/#!topic/nrf24-arduino/VaC2U5D1o_s

http://arduino-for-beginners.blogspot.com/2013/02/setup-nordic-nrf24l01-rf-modules-to.html


can i convert a pin into ground i recently started using Arduino uno , but to my despair , the ground pin , without which i cant do any project (or can i ) , so i thought of a possible solution , what if i could program the board to make a pin act as a ground , so what to do
straight 2 questions , what to do to convert any pin into ground
or can i ignore using the provided ground pin .
i have already tried fixing the pin but it cant be fixed because a detached pin has got stuck into it

Can I convert any pin into ground

Any of the digital outputs can be set LOW but there is a limit on how much current they can sink,
This makes this approach unsuitable for most use cases other than charlieplexing LEDs and similar low-current applications.
It would be better to

use any of the other ground connections.

two between Vin and 5V
one between Aref and 13
one on the 2x3-pin ICSP header for the 328
one on the unlabelled 2x3-pin ICSP header for the 16U2
one in the power jack

replace the damaged header using solder-wick and a soldering-iron.
solder a wire from a suitable ground pad on the PCB

e.g. from the ground pad for the 2.1mm power connector.

The ATmega328P data sheet says

Although each I/O port can sink more than the test conditions (20mA at VCC = 5V, 10mA at VCC = 3V) under steady
state conditions (non-transient), the following must be observed:
ATmega328P:
1] The sum of all IOL, for ports C0 - C5, should not exceed 100mA.
2] The sum of all IOL, for ports B0 - B5, D5 - D7, XTAL1, XTAL2 should not exceed 100mA.
3] The sum of all IOL, for ports D0 - D4, should not exceed 100mA.
If IOL exceeds the test condition, VOL may exceed the related specification. Pins are not guaranteed to sink current greater than the listed test condition

So no more than 20mA from or into any single pin over a long time. And no more than a total of 100 mA from or into a group of pins.


Hi-speed external ADC I would like to detect signals in nanosecond scale. For that, an ADC with at least 500 MSPS is required.

My question is if its possible to use an external ADC with 500 MSPS with a 16MHz Arduino Mega? If not, is there any additional hardware like FIFO buffer to overcome this problem?

Please help, thanks!

No, it's certainly not possible to directly sample at 500Msps on an Arduino using an external ADC.  Simple maths:

The Arduino can perform 16 million instructions (best case) per second
The ADC performs 500 million samples per second.
500 / 16 = 31.25

Therefore the ADC would be generating 31.25 samples for every clock of the Arduino, so unless you can build in a time compressor (maybe with a flux capacitor too), it just ain't gonna do it.

So you will have to think creatively instead.  A possible solution would involve:

A high speed flash or pipelined ADC, ideally with parallel output.
A large chunk of memory to act as a buffer.
A high speed clock source to set the timing (500MHz?).
Glue logic and counters to take one sample, store it in the buffer, and increment the buffer address.
More glue logic and interfacing to allow the Arduino access to the buffer memory and to control the operation of the sampling system.

This, to me, sounds like a job for an FPGA, and at 500MHz, quite a fast FPGA.  You should investigate some of the FPGA development boards from Xilinx and Altera.


Connecting the cathode of a diode to the output of a multiplexer From the image, the diodes share the same anode which is driven by 'Do Something'. My question is: through using Arduino IDE, what code should I write that connects the output of the multiplexer (Z) to a specific diode's cathode (Y0 or Y1 or ... or Y7), which in turn is connected to 'Do Something' that drives the cathode probably? In this code, I want the ESP32 microcontroller to connect this cathode to 'Do Something' for say 3 seconds and then switch to the next diode's cathode with a delay of 0.1 seconds [where no diodes' cathodes are connected to Z]       (and so on: in a continuous loop).
Here some code I found online but not sure what needs to be added to get the proper functionality:
int outputs[4] = {4,0,2}; // pins for selecting LED
int inhibit_pin = 15; // pin for turning off all LEDs

void setup() {
  for(int i;i<3;i++){
    pinMode(outputs[i],OUTPUT); // output selection for LED control
  }
  pinMode(inhibit_pin,OUTPUT);
  digitalWrite(inhibit_pin,LOW); // raise high to disable all

}

void loop() {
  // looping through all 8 LEDs
  for (int j=0;j<8;j++){
    // turn on LEDs based on bit conversion
    for(int i=0;i<3;i++){
      digitalWrite(outputs[i],bitRead(j,i));
    }
    delay(100); // delay .1 sec
  }
}

I don't think that "digitalWrite(outputs,bitRead(j,i));" is actually needed and I am not quite sure of what it does.

The code you have posted should loop through the 8 possible MUX in/out pins (Y0...Y7) connecting one at a time to pin 3.
Assuming your Y0 through Y7 are each connected to a pin on your "do something" block, the mux should connect each of the 7 pins on your "do something" to Z.
One problem I see is that your code changes the pin select values on the MUX while the MUX is enabled. As you execute your for(int i=0;i<3;i++) loop and toggle the different select bits to S0...S2, the MUX will connect different Y0...Y7 pins to Z, until it settles on the final set of values for S0...S2. You should really set inhibit_pin to HIGH (disabling the mux before entering your for(int i=0;i<3;i++) loop, and then set it to LOW again at the end of the i loop and before the delay. (to re-enable the MUX at the now-completely-selected pin.)
Your description is a little hard to follow, but it sounds like that is what you want.
If you want each pin to be connected for 3 seconds, then not connected to any pin for .1 seconds before moving on to the next pin, you might rewrite your loop like this:
void loop() {
  // looping through all 8 LEDs
  for (int j=0;j<8;j++){

    // disable the mux while selecting a pin
    digitalWrite(inhibit_pin,HIGH);

    // select a MUX pin
    for(int i=0;i<3;i++){
      digitalWrite(outputs[i],bitRead(j,i));
    }
    // re-enable the mux now that we've selected a pin
    digitalWrite(inhibit_pin,LOW);

    delay(3000); // leave the pin active for 3 seconds.

    // disable the mux for .1 seconds
    digitalWrite(inhibit_pin,HIGH);
    delay(100);
  }
}


What controller should i use? I'm working on a little DIY project in which I intend to make my own dataglove. Now I'm kinda stuck on choosing the right microcontroller. And since it can be quite costly, I thought to ask for some help.

So: I'm going to use 12 flex sensors (maybe 14) and 1 IMU (probably the 6050). now the problem is that I need a total of at least 14 AI.. And the small controllers only have about 6.

The controller can't be too big for dexterity reasons and also will need the availability to add a Bluetooth module.

I've been looking at some multiplexing/shield options but I'm just not confident (and rich) enough start ordering..

Peace out,

Lars

PS: other brands besides Arduino work for me to

How about a Teensy? The guys that make Teensy have developed many of the well known Arduino libraries and have also helped develop the Arduino IDE in the past so they know their stuff.

I see the Teensy LC at about $11. the spec says its almost the same as Teensy 3.1 which has 20+ Analog In

https://www.pjrc.com/store/teensylc.html

https://www.pjrc.com/teensy/index.html

The 3.1 and 3.6 are more powerful and more expensive at around $29

note: Read the index for which boards are 5v tolerant if that's what you need.


Unable to flash Arduino when TXD pin of HC-6 Bluetooth module is connected to Arduino RXD pin? Unable to flash Arduino when TXD pin of HC-6 Bluetooth module is connected to Arduino RXD pin?
I get the following error:

Flashing with command:C:/Users/home/.arduino-create/arduino/avrdude/6.3.0-arduino9/bin/avrdude.exe -CC:/Users/home/.arduino-create/arduino/avrdude/6.3.0-arduino9/etc/avrdude.conf -q -q -patmega328p -carduino -PCOM4 -b57600 -D -Uflash:w:C:/Users/home/AppData/Local/Temp/arduino-create-agent051272951/sketch_jun10a.hex:i
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x48

Most* Arduino devices are flashed through a bootloader which communicates over the serial pins. If you've connected another device to those pins, that communication may fail. You may need to disconnect the device while you flash the Arduino.

(*: The exceptions are the 32u4-based devices, like the Leonardo and Micro. These communicate directly over USB.)


Decode rf remote signals with ESP32 or node MCU? I'm trying to decide my rf remote signals using ESP32 or node MCU. I have tried with Arduino and was successful but for some reason it is not working on either ESP32 or node MCU even using the same GPIO2 pin can anyone please tell me why both the boards are not able to decode the signal. I'm using the rc-switch library to decode and a 433Mhz transmitter reciever combo from amazon

RCSwitch mySwitch = RCSwitch();

void setup() {
  Serial.begin(9600);
  mySwitch.enableReceive(0);  // Receiver on interrupt 0 => that is pin #2
}

void loop() {
  if (mySwitch.available()) {
    output(mySwitch.getReceivedValue(), mySwitch.getReceivedBitlength(), mySwitch.getReceivedDelay(), mySwitch.getReceivedRawdata(),mySwitch.getReceivedProtocol());
    mySwitch.resetAvailable();
  }
}```

For ESP32, you should provide real GPIO number.
For instance:
mySwitch.enableReceive(13);
And without deep explanation, believe that it properly works
with GPIO 13 and 27.
Details you can find by google...


Create one server in AP mode and another in station mode I'm trying to connect one ESP8266 to WiFi as a WebServer in station mode and to another ESP8266 as a server (that has no web pages) in AP mode.

The problem is both servers are being created in AP mode, between the ESP's, while one of them (the webserver) should be created in station mode and accessible from WiFi. The only way I can reach the webserver is connecting to the AP and accessing its IP (as access point) from my computer.

What I wanted was to access the webserver connected to my WiFi using the IP that my router gave to the hosting ESP, while the two of them would communicate using the server without web pages.

I've already tried using the same IP for both servers, inverting the order of creation of the servers and using both ESP8266WiFi.h and ESP8266WebServer.h. I've read something about the later not working with too much code inside the loop and, since the web page I want is pretty simple, I'm using ESP8266WiFi.h. Here's my code:

#include <ESP8266WiFi.h>
//#include <ESP8266WebServer.h>

WiFiServer internalServer(81);
WiFiServer externalServer(80);
//ESP8266WebServer externalServer(80);
IPAddress IP(192, 168, 4, 15); // Default IP for the AP mode, the one I'm using.
IPAddress mask = (255, 255, 255, 0);
WiFiClient internalClient;
WiFiClient externalClient;

void setup() {

  Serial.begin(115200);

  pinMode(LED_BUILTIN, OUTPUT);

  WiFi.mode(WIFI_AP_STA);

  // Config. AP mode:
  WiFi.softAP("my-access-point", "my-password");
  WiFi.softAPConfig (IP, IP, mask);

    // This connection is ok:
  internalServer.begin();
  Serial.println("Internal server created.");
  while (!internalClient) { // waiting for the internal client to connect before continuing. This works fine.
    internalClient = internalServer.available();
  }
  Serial.println("Internal client found.");

  // Config. STA mode:
  Serial.print("Connecting to Wi-Fi");
  WiFi.begin("my-wifi", "my-wifi-password");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }
  Serial.println(" Ready.");

  // Config. external server.
    // This connection isn't working
  externalServer.begin();
  Serial.print("External server created with IP: ");
  Serial.println(WiFi.localIP()); // This is the IP I expected to use to connect to the external server.
                                  // But it is accessible at 192.168.4.15.

void loop() {
  // handling external client:
  externalClient = externalServer.available();
  if(!externalClient) { return; } // proceed only when there is a request.
  String request = externalClient.readStringUntil('\r');
  Serial.println("Request: " + request);

  // The answer is just a hello world:
  String answer = "..."
  externalClient.println(answer)
  Serial.println("Answer: " + answer);

  handleInternalClient();
}

The internal client is supposed to turn on the builtin led when it receives "on" from the server and turn it off when it receives "off", and that is working fine so I think the code for it isn't necessary. If you need it, please ask.

What I want is the other ESP talking to this one through 192.168.4.15 in the AP network and my computer talking to it through whatever IP my router gives to it, in my WiFi.

It is not documented, but you can construct WiFiServer or ESP8266WebServer with IP address. If you use the IP address of the AP, the server will be available only on the SoftAP. If you use the IP address of the station, the server will be available only on STA interface.

If the IP of the interface is known before setup(), you can simply define WiFiServer internalServer(apIP, 81); instead of WiFiServer internalServer(81);. But if the IP must be first evaluated in setup() (from DHCP, or config file), then the following example shows how to set WiFiServer IP and port in setup().

#include <ESP8266WiFi.h>

WiFiServer internalServer(81);
WiFiServer externalServer(80);

void setup() {
  ...
  internalServer = WiFiServer(WiFi.softAPIP(), 81);
  externalServer = WiFiServer(WiFi.localIP(), 80);
  internalServer.begin();
  externalServer.begin();


Converting hexadecimal string to floating point value I am reading data from an energy meter over modbus protocol and I am getting hex values from there. I want to convert that hex string to floating point value.
For example - 0x416f0000 denotes a value of 14.9375.Reference

Can anyone please help me how to do it on Arduino IDE?

If you do indeed have an ASCII string of hexadecimal numbers (and not a
raw binary float), then your best option may be to do the conversion in
two steps:

convert the string to a 32 bit unsigned number using
strtoul()
reinterpret the binary pattern of this integer as a float.

For example, the following program:

void setup() {
    const char modbus_data[] = "416F0000";
    union {
        uint32_t i;
        float f;
    } data;
    data.i = strtoul(modbus_data, NULL, 16);

    Serial.begin(9600);
    Serial.println(data.f, 4);
}

void loop(){}

prints 14.9375.

Note that for strtoul() to function properly, the hex string must be
followed by a character that is not a valid hex digit (a \0 in the
example above).


Finding Relatively Accurate Velocity Using an IMU I am currently working on a project where I am trying to accurately find velocity in a handheld device using an IMU for about 30 seconds.
I have been having major issues doing this because of large amounts of drift from poor calculations due to inaccurate sensor readings.
I have tried tuning offsets for my sensor and using other sensor fusion libraries to find my linear acceleration.
At this point I don't know if I am doing something wrong, going about the process wrong, or if my sensors are just to inaccurate to accomplish this.
I am hoping if anyone may have recommendations on how to accomplish this from the ground up. I currently have two 9DOF IMUS listed below. The first one I tried to use the predefined linear acceleration function to find velocity in ndof mode, using bosch calibration steps. The second i spent hours tuning the offsets on to get linear acceleration and it came out much worse than the first sensor. For the second I can include code but I used the madgwick from the Adafruit_AHRS library for the sensor fusion for sake of time.
Any help is appreciated.

https://www.adafruit.com/product/4646 (BNo055 first board)
https://www.adafruit.com/product/3463 (FXOS8700 + FXAS21002 second board)

Integration of acceleration to derive velocity is a difficult task.  This is the first step in dead reckoning.  Consider some of the following options to improve accuracy:

Some IMUs can be adjusted to increase sample speed. If the
acceleration is sudden, more samples my improve the accuracy of the
calculated velocity.
Try aligning just 1 of the axes of the IMU chip in the direction of
acceleration. Do this to simplify the problem.  Depending on the
Arduino you are using, the processor may not have the power to
perform the trig functions necessary for anything except
acceleration only along 1 of the IMU's axes.
Take care of loosing significant digits.  If using integers, try
multiplying everything up.  For example instead of 1 equaling 1
meter multiply the value up such that 1000 equals 1.000 meters.  Now
integer math can be used to calculate down to the mm.


Return photo stacking rail to start In isolation (73 years old) and trying to get my macro photo stacking rail to return to start without a limit switch.  I know the number of steps taken, so it is just a matter of reversing the motor.  My code (copied and pasted from other sites) works like a dream (10 steps, fire an IR camera trigger) and continues up to when I want to return (line 73) taking 100 shots or steps however many I want - no problem.

I started a void return loop (and terminated the loop) but the coding has me beat.  I have attached my code (might look terrible, but it works).  Can anyone help out this old guy and give me the code to counter clockwise 1000 steps?

Thanks fellas
David

[code]
#include <AccelStepper.h>
#include <MultiStepper.h>

int smDirectionPin = 2; //Direction pin
int smStepPin = 3; //Stepper pin
int Distance = 0; // records the number of steps we have taken
byte numRepeats = 0;
byte maxRepeats = 100;
int smFirePin = 13;  //Trigger pin
#define fire 13

 void setup(){
  /*Sets all pin to output; the microcontroller will send them(the pins) bits, it will not expect to receive any bits from thiese pins.*/
  pinMode(2, OUTPUT);  //Direction Pin
  pinMode(3, OUTPUT);  //Step Pin
  pinMode(13, OUTPUT);  //LED pin
  digitalWrite(2, LOW);
  digitalWrite(3, LOW);
  digitalWrite(13,LOW);
  pinMode(smDirectionPin, OUTPUT);
  pinMode(smStepPin, OUTPUT);

  Serial.begin(9600); //Open Serial connection for debugging
}

void loop(){
   if (numRepeats < maxRepeats) {
   move1Step();
   Distance = Distance + 1; //record this step to see if we are et the end of our move

  if (Distance == 10)
  {
 if (digitalRead(2) == LOW)
 {
  digitalWrite(2 , LOW);
 }
 else
 {
  digitalWrite(2, LOW);
 }
 Distance = 0;
 numRepeats ++;
 delay(3000);
{
    trigger();
}
   }
 }
}
void move1Step() {
  digitalWrite(3, HIGH);
  delayMicroseconds(750);
  digitalWrite(3, LOW);
  delayMicroseconds(750);
}
// Power on the IR trigger circuit to fire the camera
void trigger()
{
    delay(1000); // wait for vibration to settle
    digitalWrite(fire, HIGH); // take the picture
    delay(2000); // wait for that to happen
    digitalWrite(fire, LOW); // disable the IR circuit again
}

// Advance the motor by one step
void step()
{
  digitalWrite(step, HIGH); //Trigger one step forward
  delay(1);
  digitalWrite(step, LOW); //Pull step pin low so it can be triggered again
  delay(1);
}

  void return();

{
  digitalWrite(smDirectionPin, HIGH);
  /*Slowly turns the motor 1600 steps*/
  for (int i = 0; i <200; i++){
    digitalWrite(smStepPin, HIGH);
    delayMicroseconds(700);
    digitalWrite(smStepPin, LOW);
    delayMicroseconds(700);
  }

  while(1) { }
}

[/code]

I cleaned up your code a bit. Removed duplicate and unused code. I used a for-loop to make it run for 100 repetitions.

Feel free to let me know if you have any more questions, or if there are things that aren't clear.

// You aren't using these libraries, so I commented them out
//#include <AccelStepper.h>
//#include <MultiStepper.h>

int smDirectionPin = 2; //Direction pin
int smStepPin = 3; //Stepper pin
int smFirePin = 13;  //Trigger pin

byte maxRepeats = 100;

void setup()
{
  /*Sets all pin to output; the microcontroller will send them(the pins) bits, it will not expect to receive any bits from thiese pins.*/
  pinMode(smDirectionPin, OUTPUT);  //Direction Pin
  pinMode(smStepPin, OUTPUT);  //Step Pin
  pinMode(smFirePin, OUTPUT);  //Fire pin
  digitalWrite(smDirectionPin, LOW);
  digitalWrite(smStepPin, LOW);
  digitalWrite(smFirePin,LOW);

  Serial.begin(9600); //Open Serial connection for debugging
}

void loop()
{
  digitalWrite(smDirectionPin, LOW); // set stepper motor to run forwards

  for( byte i=0; i<maxRepeats; i++ ) // run the following section 100 times
  {
    //move 10 steps forward
    for( byte j=0; j<10; j++ )
    {
      move1Step();
    }

    // wait and take a photo
    delay(3000);// there is already a delay in the `trigger` function, so this like could be removed
    trigger();
  }

  // return the stepper motor to the starting position
  digitalWrite(smDirectionPin, HIGH); // set stepper motor to run in reverse
  for( byte i=0; i<maxRepeats; i++ ) // run the following section 100 times
  {
    //move 10 steps backwards
    for( byte j=0; j<10; j++ )
    {
      move1Step();
    }
  }

  // Do nothing
  while(1){ }
}

void move1Step()
{
  digitalWrite(smStepPin, HIGH);
  delayMicroseconds(750);
  digitalWrite(smStepPin, LOW);
  delayMicroseconds(750);
}

// Power on the IR trigger circuit to fire the camera
void trigger()
{
    delay(1000); // wait for vibration to settle
    digitalWrite(smFirePin, HIGH); // take the picture
    delay(2000); // wait for that to happen
    digitalWrite(smFirePin, LOW); // disable the IR circuit again
}


Serial monitor doesn't work with piezo buzzer So I can't see the distance of the proximity sensor anymore as soon as I type the code for the piezo buzzer. I've tried many things but it doesn't work.. Can anybody help me fixing this?

int trigPin = D7;
int echoPin = D8;
int BLUE = D3; //D3 zit in blauw
int GREEN = D4;
int RED = D5;
int piezoPin = D10;

void setup() {// deze code gaat maar 1 keer
  Serial.begin (115200);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);

  pinMode(GREEN, OUTPUT);
  pinMode(BLUE, OUTPUT);
  pinMode(RED, OUTPUT);

}

void loop() { //code wordt steeds herhaalt
  long duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH); // trig zendt een signaal uit
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH); // kijkt hoelang het duurt totdat signaal heen en weer gaat
  distance = (duration/2) / 29.1;
  // omdat het signaal heen wordt gezonden moet het door twee gedeelt worden
  // snelheid van geluid door lucht is circa 29 microseconden per cm dus gedeelt 29.

    Serial.print(distance);
    Serial.println(" cm");

//afstand wordt in cm weergegeven in serial monitor

  delay(500);

   if ((distance > 100) && (distance <= 150)){ //dit gebeurd er als de afstand vanaf sensor tussen groter dan 100 cm en gelijk aan of kleiner dan 150 cm is.
    analogWrite(BLUE, 0);
    analogWrite(GREEN, 255);
    analogWrite(RED, 0);

    tone(piezoPin, 1000, 1000); // toon duurt 1 seconden
    delay(2000); // 2 seconden geen geluid
    tone(piezoPin, 1000, 1000);
    delay(2000);

   }

   else if ((distance > 50) && (distance <= 100)){ //dit gebeurd er als de afstand vanaf sensor tussen groter dan 50 cm en gelijk aan of kleiner dan 100 cm is.
    Serial.println("Ga weg!");

    analogWrite(BLUE, 0);
    analogWrite(GREEN, 102);
    analogWrite(RED, 252);

    tone(piezoPin, 1000, 700); // toon duurt 0.7 seconden
    delay(1000); // 1 seconde geen geluid
    tone(piezoPin, 1000, 700);
    delay(1000);

  }

  else if ((distance >= 0) && (distance <= 50)){ //dit gebeurd er als de afstand vanaf sensor tussen groter dan of gelijk aan 0 cm en gelijk aan of kleiner dan 50 cm is.

    analogWrite(BLUE, 0);
    analogWrite(GREEN, 0);
    analogWrite(RED, 255);

    tone(piezoPin, 1000, 200); // toon duurt 0,2 seconden
    delay(100); // 0,1 seconden geen geluid
    tone(piezoPin, 1000, 200);
    delay(100);

  }

   else {
    analogWrite(BLUE, 0);
    analogWrite(GREEN, 0);
    analogWrite(RED, 0);

 }

}

Pin D10 of NodeMcu is io 1 which is RX pin of Serial interface of the esp8266. Serial is on NodeMCU connected to USB. The pin is on board labeled RX.

D8 is boot config pin io 15. It must have pulldown on board. The pulldown can disturb the input on this pin. Use D6 (io 12) as echoPin.


Operating system on Atmel 328 Arduino? Is it possible to use some sort of multitasking OS like ScmRTOS on Arduino based on Atmel 328 chip?

You can use FreeRTOS on the AVR family:

http://www.freertos.org/a00098.html


Controlling keyboard LEDs with USB Host Shield I've got a USB keyboard connected to my Arduino Uno with a USB Host Shield. I'm reading keystrokes using this example from the USB Host Shield library.

I need to toggle the LEDs in the keyboard (that indicate the state of Caps Lock, Num Lock etc.)

This thread mentions using Usb.setReport(), but this method doesn't seem to exist any more: there's no such method in Usb.cpp in the library. There does seem to be a method called SetReport in the USBHID class, which looks like it takes the same arguments, which I'm trying to use.

What I'm currently doing:

void keyboard_setup(){
    static HIDBoot<USB_HID_PROTOCOL_KEYBOARD> HidKeyboard(&Usb);
    if (Usb.Init() == -1) {
        Serial.println("OSC did not start.");
    }
    delay(200);
    HidKeyboard.SetReportParser(0, &Prs);

    static USBHID usbhid(&Usb);
    uint8_t leds = 1;
#define KBD_ADDR 1
#define KBD_IF 0
    usbhid.SetReport( KBD_ADDR, 0, 1, KBD_IF, 0, &leds );
    delay(100);
    leds = 255;
    usbhid.SetReport( KBD_ADDR, 0, 1, KBD_IF, 0, &leds );
    delay(100);

Neither call to SetReport seems to work, and I'm not certain the values of KBD_ADDR or KBD_IF are correct (I'm using ones that I've seen in examples), or event that calling SetReport is right .

What am I doing wrong?

There does seem to be a method called SetReport in the USBHID class, which looks like it takes the same arguments, which I'm trying to use.

The method arguments of the new SetReport() method aren't quite the same and some are in a different order.
The old method signature was:
uint8_t setReport( uint8_t addr, uint8_t ep, unsigned int nbytes, uint8_t interface, uint8_t report_type, uint8_t report_id, uint8_t* dataptr );

...while the new one is:
uint8_t SetReport(uint8_t ep, uint8_t iface, uint8_t report_type, uint8_t report_id, uint16_t nbytes, uint8_t* dataptr);

It seems to me the equivalent call would be:
usbhid.SetReport( 0, KBD_IF, 0x02, 0, 1, &leds );


How is interaction with CDC device with no interface endpoints working? I'm working on uploading to Digispark board. It uses micronucleus bootloader and i can see uploader code. I've modified it a bit to see interfaces and endpoints count:

    nucleus->device = usb_open(dev);

    // added by me - start
    int interfaces, endpoints, j;
    struct usb_interface_descriptor *interface = NULL;

    interfaces = dev->config->bNumInterfaces;
    fprintf(stderr, "Found interfaces: %i\n", interfaces);

    interface = &(dev->config->interface[0].altsetting[0]);
    fprintf(stderr, "Endpoints: %i\n", interface->bNumEndpoints);
    // added by me - end

    // get nucleus info
    unsigned char buffer[4];
    int res = usb_control_msg(nucleus->device, USB_ENDPOINT_IN| USB_TYPE_VENDOR | USB_RECIP_DEVICE, 0, 0, 0, (char *)buffer, 4, MICRONUCLEUS_USB_TIMEOUT);

I wonder how it's working because interface #0 has no endpoints:

$./micronucleus --type intel-hex /tmp/Start.ino.hex
> Please plug in the device ...
> Press CTRL+C to terminate the program.
Found interfaces: 1
Endpoints: 0
> Device is found!
connecting: 40% complete
> Device has firmware version 1.6
> Available space for user applications: 6012 bytes
> Suggested sleep time between sending pages: 8ms
> Whole page count: 94  page size: 64
> Erase function sleep duration: 752ms
parsing: 60% complete
> Erasing the memory ...
erasing: 80% complete
> Starting to upload ...
writing: 100% complete
>> Micronucleus done. Thank you!

Usually i expect interface to have 2 endpoints (in & out from usb.h):

#define USB_ENDPOINT_IN         0x80
#define USB_ENDPOINT_OUT        0x00

Can anyone explain me how usb_control_msg(nucleus->device, USB_ENDPOINT_IN| USB_TYPE_VENDOR | USB_RECIP_DEVICE, 0, 0, 0, (char *)buffer, 4, MICRONUCLEUS_USB_TIMEOUT); is working without endpoint?

Micronucleus uses control transfers to upload code (it's not a CDC device). You don't need an endpoint for control transfers - they use the implicit endpoint 0 that is always present whether you define one or not.

You only need to define endpoints for interfaces that want to communicate using bulk, interrupt or isochronous transfers.

Bus 003 Device 073: ID 16d0:0753 MCS Digistump DigiSpark
Device Descriptor:
  bLength                18
  bDescriptorType         1
  bcdUSB               1.10
  bDeviceClass          255 Vendor Specific Class
  bDeviceSubClass         0
  bDeviceProtocol         0
  bMaxPacketSize0         8
  idVendor           0x16d0 MCS
  idProduct          0x0753 Digistump DigiSpark
  bcdDevice            1.02
  iManufacturer           0
  iProduct                0
  iSerial                 0
  bNumConfigurations      1
  Configuration Descriptor:
    bLength                 9
    bDescriptorType         2
    wTotalLength           18
    bNumInterfaces          1
    bConfigurationValue     1
    iConfiguration          0
    bmAttributes         0x80
      (Bus Powered)
    MaxPower              100mA
    Interface Descriptor:
      bLength                 9
      bDescriptorType         4
      bInterfaceNumber        0
      bAlternateSetting       0
      bNumEndpoints           0
      bInterfaceClass         0 (Defined at Interface level)
      bInterfaceSubClass      0
      bInterfaceProtocol      0
      iInterface              0
Device Status:     0x18c0
  (Bus Powered)
  Debug Mode


Burning Arduinos one after another I very accidentally caused a short-circuit to two completely different cheap (under 4$ each) Arduino Uno clones, rendering Windows sound alert for unplugged USB several times.

This subsequently led to a problem with uploading code and not blinking green light on reset on both the Arduinos. Now, I am aware what this means but I am unable to see why this happens. I thought it has protection against that.

Is it normal for them to react like that so easily? How can I prevent this happening AGAIN?

Measurements to prevent breaking an Arduino (or AVR in general):

Precautions

Always remove the USB or adapter plug when you make a change in the circuit.
Check all wires before you switch it on.
Remove or make sure (temporary) loose wires/jumpers do not touch other components or the Arduino (better take them out or 'park' them somewhere else in the breadboard.

Preventing wanted changes resulting in shortcuts

Check again the wires/jumpers you just changed/added.
Make sure no other components/wires/jumpers are touching the Arduino or the breadboard (components).
Clean your desk (if you have space), so if something metal falls/moves, it does not hurt your Arduino.
When changing a shield, always check all wiring to and from it, to your Arduino and the components on the shield itself if needed.

Preventing component shortcuts or overpowering

If you have a wire from a pin to GND or a pin to VSS, always make sure there is either a resistor, or you know why a resistor is not needed. This can also damage directly your Arduino.
Make sure that every component does not get more power than it can handle.
More specific: If you have components using 3.3V, make sure they don't get 5V.
If you have components using 3.3V, make sure they don't get 5V.

Preventing too much heat

Do not just put an Arduino in some case/enclosure ... heat may destroy it, so check before there is enough cooling, add a fan, heatsink or make holes in the enclosure.
If you connect any power source other than USB, check again if it does not generate unnecessary much heat. Unused voltage will generate much heat.

Preventing static electricity

Do not touch components when not needed
If you touch components, make sure you are discharged (touch a radiator, use a wrist band, use an ESD mat, touch grounded wire).

Preventing trivial mistakes

Do not keep drinks next to your Arduino or breadboard (or if you, keep it on the other side).
Watch out for heavy cables not dragging your Arduino from the table/desk ... a USB cable can easily drag an Arduino down.
Watch out when you change cables, not to pull your Arduino from the table/desk.
Keep animals (and people too, to your own judgement) away from your electronics project.


Making MCUs Arduino Compatiable I have recently just built a custom arduino using the schematics found on their website. As awesome as this little processor is, I need more power. I have been thinking of making my own MCU, but wanted to know if it is possible to make them compatible with the arduino software. It would be very nice to not have to rewrite my existing programs.

If so, how would I go about doing that? If this is not a possibility (or just not a good idea for any reason), which language should I learn to start programming these upper level MCUs.

If I do have to start using a different language, what kind of software do I use to upload the code to these processors? And do they have the common features like Serial Monitor and Serial Plotter like the Arduino IDE does.

You are speaking of porting. The arduino environment is built around a set of libraries and commands that are designed to abstract the low level access to a simpler high level language. In order to make arduino code work on a new microcontroller, you would have to rewrite and recreate the libraries using the low level access of your target microcontroller.

For example, Energia is a port of the Arduino libraries to the Texas Instruments MSP430 line of microcontrollers. Since not all features are the same, some code does not just drop in directly but additional code or libraries could be added to fix that. Even the Arduino IDE, the program used to write code and program the arduino was ported.

It would not be a trivial thing to port an entire library base.

As to your other questions, you would code your new microcontroller in any language it's programmer and compiler can use. Likely C or C++. Arduinos are typically programmed in C++. You should look into the manufacturer of your MCU to find out what software to use, and what libraries they offer. They likely do not offer something like the serial monitor right out of the box.


Controlling a button I'm going to write a sketch that would light up the first LED (D1) of the training shield at the beginning, then move the LED light to the left or to the right whenever you press the S1 or S2 buttons, respectively. When the LED is already at the first (D1) or the last (D8), it should no longer move when going further to the left or right, respectively.

Looks exactly like this: https://www.youtube.com/watch?v=_KQQTdDMgOU

Here's what I made so far:

int x = 0;

void setup() {
  for(int i=11; i <= 18; i++) {
    pinMode(i, OUTPUT);
  }
}

void loop() {
  x = digitalRead(pushButtonPin);
  if (pushButtonState == HIGH) {
    // turn LED on:
    digitalWrite(ledPin, HIGH);
  } else {
    // turn LED off:
    digitalWrite(ledPin, LOW);
  }
}

What you made so far is only turn on and off LED according to button state. I believe there's more efficient code out there, but you can try:

int x = 11;

 void setup() {
 for(int i=11; i <= 18; i++) pinMode(i, OUTPUT); //assuming the led is on pin 11-18
 }

 void turnLED(int num)
 {
     for(int i=11; i <= 18; i++)
         if (num==i) digitalWrite(i,HIGH); else
                     digitalWrite(i,LOW);
 }

 void loop() {

    if (digitalRead(buttonRight))
    {
        x++;
        if (x>18) x=18;
    }
    else if (digitalRead(buttonLeft))
    {
        x--;
        if (x<11) x=11;
    }
    turnLED(x); //turn LED on according to value of 'x'
    delay(500);
}


Why does the Leonardo take 8 seconds to restart? My problem is, that my system takes 8 seconds to start the programm after I push the Reset button on my Leonardo.
During that period the L-LED is pulsating.

What could be the problem?

That's the firmware waiting for a programming connection. If you want alternate behavior them burn SparkFun's ATmega32U4 firmware to it. One press of Reset will reset the device, and two presses will put it into programming mode.


Can the Sparkfun AVR pocket programmer bootload/program a 3.3 V ATmega328p The product in question - https://www.sparkfun.com/products/9825 - operating at 5 V (and can also supply it to the device being programmed).

I need to program the bootloader onto a 3.3 V ATmega328p and don't have any level shifters immediately available. Thus the question. The "Hookup Guide" for the product (https://learn.sparkfun.com/tutorials/pocket-avr-programmer-hookup-guide) seems to suggest that it will work fine as long as the 3.3 V device being programmed isn't powered by the programmer. I wouldn't have thought it's the best idea in the world, but maybe I'm wrong.

So any practical experience?

Are the over voltage tolerances for input lines on Atmel devices good enough to handle the extra voltage?

I guess the output level from the device being programmed would be high enough to be buffered up to 5.0 V?

With that combination of programmer and Arduino you have two possible options:

Cut JP1 on the programmer and power the programmer from the Arduino. With this you will have to make sure that the Arduino is connected and powered up before you connect the programmer to USB.
Cut SJ1 on the Arduino and allow it to be powered by the programmer at 5V. The Arduino itself isn't required to be powered at 3.3V, that's simply what the on-board regulator provides, so we cut SJ1 in order to isolate the regulator from the MCU. Note that any devices connected to the Arduino will need to support 5V operation in order to this to be safe.

It is not safe to put 5V at the output of the regulator, so you must make sure that does not happen.