Problems with controlling LED with soil moisture sensor I'm a beginner at Arduino.

I have a soil moisture sensor and I mapped the lowest and highest moisture value to a value in between 0 and 100.

What I was trying to do was if the value was less than 50, then the LED should turn on. But even when the value was less than 50 (e.g 25) the LED doesn't turn on.

The moisture detection or the value mapping works perfectly fine.

Does the issue lie on my code or my LED wiring?

Code:

int mostMoist = 180;
int leastMoist = 600;
int percent;
int raw;
const int threshold = 50;

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

void loop() {
  raw = analogRead(A0);
  percent = map(raw,leastMoist,mostMoist,0,100);

  if (percent < 0){
    percent = 0;
  }

  if (percent < threshold){
    digitalWrite(LED_BUILTIN,HIGH);
  } else {
    digitalWrite(LED_BUILTIN,LOW);
  }

  Serial.println(percent);
  delay(2);
}

A good way to start debugging this sort of problem is to print out debug statements that say what the hardware should be doing. If the debug statements print out as expected then it's probably hardware, if not, then it's probably your code, e.g.

if (percent < threshold){
  Serial.prinln("LED on.");
  digitalWrite(LED_BUILTIN,HIGH);
}
else {
  Serial.prinln("LED off.");
  digitalWrite(LED_BUILTIN,LOW);
}


What are patterns of bits sent to or read from GPIO pins called? I want to call them “words”, but I’m uncertain if this is how they are referred to in documentation for the use of a header board that might plug into an ardino board.
So if you have a sequence of ONs and OFFs being read or sent from a microcontroller board are those called words?  What are they called?

Here is a simplistic diagram.
Larger than 8 bits is usually referred to as WORD.


How to bootload a atmega328-pu using arduino uno? I have some Atmega328-Pu micro-controllers without boot-loader program. Now I need to burn boot-loader to them all. I have two arduino uno boards having Atmega328 P-Pu micro-controllers on board. I used this circuit  from this page Installing an arduino boot-loader
It does not work. The boot-loader is not uploaded. Can you please help me out? If you need any more informations please ask. I have been struggling with this kind of boot-loading techniques for more than a week. I am using arduino IDE 1.0.1 and the board is Arduino uno R3

Hi friends thanks for your support. It worked well as it is. No external capacitor I used.
I made the connection as shown in the above picture taken from LINK1.
I modified the file "boards.txt" and "avrdude.conf" as given in step 4 of LINK2
I first uploaded the ArduinoISP sketch to the board on the left.
And then I opened an "EMPTY ARDUINO SKETCH".
From that empty sketch I made the following changes
     Tools->Board = "Arduino328"
            Port  = COM4 in my pc
            Programmer = Arduino as ISP
Last step "Burn Bootloader"
Ta Da....
It worked. When I posted this question I burnt the boot-loader having the arduino ISP sketch opened. Only thing I changed now is I opened an empty sketch and hit burn from that sketch. Anyway.. thank you all. I dont think I wasted your time. If so, I apologise.


Problem stacking ADS1292r ECG shield and Wifi shield on Arduino Uno I want to use ADS1292r ECG shield with Arduino Uno (Seeeduino V4.2) and store the data in an SD card through an Wifi shield. But the ADS1292r shield uses Digital pin 4 for "RESET" purposes, while the same pin is the "SD card select" pin for the WiFi shield. So if I stack all 3 of them, the SD card can't be initialized. Is there any way to solve this problem?

As a generic answer to these sorts of problems (same pin needed by different libraries), I have had success with slightly bending the pin of the top shield to the side to that it doesn't make direct contact with the board underneath (ie doesn't plug into the header socket).

Assuming the shields are all stackable, you can run a jumper wire from the top of the pin to any other pin which is permitted by the configuration. If not, you may have to solder a wire.

In your example, put the WiFi shield on top with its D4 pin bent to the side (with ECG shield between Uno and WiFi shield) , and run a jumper between the tops of D3 and D4 (ie on the WiFi Shield). Thus the SD Card select would now be set to D3 instead of D4, and no other connection is made to D4 on the WiFi shield.

I can't verify that you won't have trouble with other pins (eg it looks like both shields use D7).


Arduino freezing with OLED display I have a 0.96" OLED display hooked up to my Arduino Mega via SPI. I installed the Adafruit library and GFX library. I can run through the little graphical demo from Adafruit just fine as well as display static text with no problem.

However, I am trying to put together a project I thought would be simple and straight forward. I am trying to use a DHT22 to collect temperature and humidity and then display it on the OLED. The problem I am running into is that the Arduino freezes after an indeterminate amount of time. The most it has been able to run is about 6 minutes.

Here is the code I am using:

#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <DHT.h>

#define DHTPIN 7
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);

// If using software SPI (the default case):
#define OLED_MOSI   8
#define OLED_CLK   9
#define OLED_DC    10
#define OLED_CS    11
#define OLED_RESET 12
Adafruit_SSD1306 display(OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS);

#define LOGO16_GLCD_HEIGHT 16
#define LOGO16_GLCD_WIDTH  16

#if (SSD1306_LCDHEIGHT != 64)
#error("Height incorrect, please fix Adafruit_SSD1306.h!");
#endif

long previousMillis = 0;
long interval = 5000;

    String temperature;
    String humidity;

void setup(){
  dht.begin();

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

  // by default, we'll generate the high voltage from the 3.3v line internally! (neat!)
  display.begin(SSD1306_SWITCHCAPVCC);

  display.clearDisplay();

  display.setTextSize(2);
  display.setTextColor(WHITE);
  display.setCursor(0,0);

  display.println(" Madgayrah");
  display.display();
  while(millis()<2000);
}

void loop() {

  unsigned long currentMillis = millis();
  if(currentMillis - previousMillis > interval) {
    previousMillis = currentMillis;

    float h = dht.readHumidity();
    float f = dht.readTemperature(true);

    if(isnan(h) || isnan(f)){
      int x = 6;
      String dashes = "";
      for(int y=1; y<=x; y++){
        dashes += "-";
      }
      temperature = humidity = dashes;
    }else{
      temperature = String(f)+(char)248;
      humidity = String(h)+"%";
    }

    display.clearDisplay();
    display.setTextColor(WHITE);
    display.setCursor(0,0);

    display.setTextSize(1);
    display.println(String(previousMillis/1000));
    display.println("");

    display.println("Temperature:");
    display.setTextSize(2);
    display.println(temperature);

    display.setTextSize(1);
    display.println("Humidity:");
    display.setTextSize(2);
    display.println(humidity);

    display.display();
  }
}

In my attempt at debugging I discovered that NOT printing out the temperature and humidity variables allows the program to run indefinitely. However, for some reason turning on either one of those lines and printing out that variable leads to the issue of the Arduino freezing.

ADDITIONAL INFORMATION:
I am using a 12 volt external power supply hooked up to the barrel of the Mega. The Mega is providing 5 volts and ground to a bread board which powers/grounds both the OLED and the DHT22.

Any ideas as to what could be causing the freezing issue on what "should be" a simple and straightforward project? Thanks.

Because your program uses various String objects in several different sizes, there's a good chance that heap memory (in RAM) is getting fragmented to the point that String allocation begins to fail, or begins to allocate on top of stack variables.  (Typically, heap and stack work toward each other, from opposite ends of memory that is free after static variables are allocated.)

For example, the code for(int y=1; y<=x; y++){ dashes += "-"; } with x=6 creates half a dozen String objects, all of different lengths.

To avoid this problem, you could carefully release each heap allocated object when done with it, or more effectively, could avoid using String objects, which actually aren't needed in this program.

For example, instead of display.println(String(previousMillis/1000)); say display.println(previousMillis/1000); and instead of building dashes a character at a time before using it, just say "------" in place of dashes.


MD_Parola display issue when constructing test I'm using ESP8266 and 4 dot Matrix Tiles, to display clock ( updates using NTP and WiFi ).
Everything is working well, but only when I'm constructing text using a const char* type.
But, since I wish to construct text as sprintf(temp, "12:00"); or char temp[20]="12:00\n; creates gibberish text.
MD_Parola dotMatrix = MD_Parola(HARDWARE_TYPE, CS_PIN, MAX_DEVICES);

void updateTime()
{
  char clk[10];
  char dat[10];
  char temp[10];
  sprintf(temp, "12:00"); // <---- this ways failes
  const char *t = "12:00"; // <---- this way succeeds
  dotMatrix.displayText(t, PA_CENTER, 0, 0, PA_PRINT, PA_NO_EFFECT);
}

link to library
Appreciate explanation how to construct text not as const char*

The library documentation states:

The library does not allocate any memory for the text message

That suggests, that the buffer has to be valid beyond the execution of the displayText() function. But as you declare it inside of your updateTime() function, it the buffer gets out of scope, when exiting that function. The memory space can then be reused by the rest of the program. At that point the library will still have the pointer to the old location, though that pointer can now be considered invalid. Thus you are just reading, what the compiler decided to place in that memory location.
To solve that, you need to keep the buffer variable in scope. You can do this by moving the declaration to the global scope.


Storing data (strings) if ethernet fails to send it Flow goes something like:

Read sensors
Send data
If send fails store the data in eeprom/flash/sd
If sent check if any previous ones have failed and send those

So my question is what's the best storage option to save the data? Is there an easy way to save strings or am I going to have to write it byte by byte?

In my opinion SD would be the best way because it is cheap, small, relatively fast and easily portable on a PC, using FAT (but it uses a lot of resources) or even raw; but then you have to use some more trick to get to the raw data from a OS, its not just "plug n read".

The SD library uses FAT under the hood, and it gives you a nice and easy interface. Just remember that SD works at 3.3V, and connecting them directly to arduino will break them fast, even if often not immediately.


Newbie question - Biltong Box Project I am a newbie to electronics, but I do have experience working with electrical wiring in the UK, so I am comfortable working with 240V reasonably safely. I have also built a camper including all the 12V electrics from scratch. I am fairly technically able, as a building physicist and academic researcher. However, my expertise is in mechanical engineering and physics rather than electronics or electrical engineering.

The Project

I am designing a new generation biltong box. My previous biltong boxes had electrical devices wired individually into plugs and then manually switched.

For those who dont know 'biltong' is the South African equivalent of US jerky. We simply dry the raw beef as opposed to light cooking.

Image 1 - first generation manually switched biltong box

The first generation boxes worked great - they were a test bed for the physics - airflow/heat and drying rates. However, they lacked finesse and were technologically challenged. So I have set myself the goal of building a new smaller box, laser cut from acrylic and packed with more intelligence.

My inspiration is drawn from this great project

Technical details

The biltong dryer design currently comprises of:

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

What I want to do / Problem Statement

I would like to have an Arduino based system, to facilitate the following features:

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

Please help

I know all the kit I am trying to control and how I want to do it (conceptually). Now I need some advice on how to make this happen please.

To kick things off I have purchased an Arduino MEGA 2560 board and kit and have experimented with a few small projects. I now want to use this to control the above.

Questions

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

Huge thanks in advance.

First Edit

My calculated current for the heater is 60W / 240V = 0.25A

Questions:

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

Second Edit

Not sure where to go from here!

Also, cannot find MOSFET's in Fritzing.

Is my idea sensible and achievable (technically)?

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

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

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

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

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

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

Yes - see above.

As far as control goes you may want to investigate PID as your calculation method.


Flow meter using Wemos Mini - ISR not in IRAM! I'm trying to use a flow meter with Wemos Mini.
Most tutorials are using Arduino boards ( which code and HW work OK ), but since I want this device to send alerts over the internet when abnormal usage/leakage is detected, I want to use Wemos Mini using How to Use Water Flow Sensor - Arduino Tutorial. On top of if will add my code for notifications using Telegram.

BUT - after uploading the original code (before adding Telegram changes ), an error occurs during code run : ISR not in IRAM!

I tried to change Pin - but still getting this error,

This happens because of conflicts between Serial and external interrupts
Put ICACHE_RAM_ATTR before your interrupt function, like this  ICACHE_RAM_ATTR void ISR()


Controllino Mega and Fatek HMI I have a setup that controls the rotation of two stepper motor using Arduino UNO, HBS860H stepper drivers, 4X4 keypad and LCD screen. I have replaced the Arduino Uno by a Controllino Mega and it works good. Now I am trying to replace the Keypad and LCD screen by a FATEK HMI PN2043NK.
I have the sketch for the Controllino,
I can use RS485 to communicate both devices.
I use FV Designer to program the HMI, but I don't understand how to run the sketch from the HMI.
I need some help with a simple example Please, any help I could use to start learning to communicate the HMI with the Controllino and run the steppers will be welcome.

The usual "sketch" is "always" running on your arduino (Controllino) unless it is put into a non-run mode (like when loading a program) or doesn't have power.  What you need in your sketch is to do something IF a command is received on the serial (RS485).  Rather than simply running the command you want, the sketch needs to check the serial and only execute the command if the HMI sent the correct signal.

For motor control, you could use G-code where your HMI sends G-code move commands over RS485 and your Controllino executes them.  A handy RS232 example is grbl.


How to power both arduino and 1 color led strip from single power source I'm trying to understand and adapt this tutorial:

https://learn.adafruit.com/rgb-led-strips/current-draw

to my own use. I am doing essentially the same thing, except I have this single color LED strip, and I don't fully understand how to power both the arduino and the led strip from the same power source.

I tried to wire it using the diagram above, and something started smoking (I think the IR transmitter). I don't know much about circuits, but I'm pretty sure that's not good.

In this diagram, the 9v represents DC power, the IR sensor on the left represents the transmitter, the IR on the right is the receiver, and the white LED is the LED strip, with two outputs (+ - )

In the fritzing diagram for that tutorial, they have the + from the LED strip going straight in to Vin on the uno, but they don't show how either the LED strip or the uno themselves are being powered.

Do I need two power sources?

Do I need a mosfet considering I'm only using a one color LED strip?

I've got the IR sensors working, so I don't need help with that, and I can connect one of these 12V switching power supplies to one of these DC power screw terminals to power the lights without any arduino control, so all I'm missing is how to turn the lights on and off with arduino, IE, how to go from the power supply to the arduino to the LED strip.

I don't need to PWM the LED strip - just shut it off and on.

If anyone can help me correct the fritzing diagram or explain what I'm doing wrong / what I should be doing instead, I'd greatly appreciate it.

Note that VIN pin and the 2.5mm DC Jack are connected. So in the tutorial one of these is getting power from a +12Vdc source and the other is supplying +12V to the +12v labeled pin on the LED string. Where the R G and B pins of the strip should be connected to Collectors of NPN's. Each of the NPN's bases are driven by Arduino Output pin and all the Emitters are connected to Ground.

So +12V supplies the DC Jack (aka Vin) the Arduino's local regulator converts that to Ground. The +12V via Vin supplies the LED's. And the Digital Outputs drive the base's of the NPN's. Which in turn act like a relay closing the perspective LED's to Ground, so they can illuminate. Where a Digital ONE or HIGH or TRUE on the BASE results in 5V above ground, which causes it to have low resistance.


Help choosing a servo motor I am struggling to choose servo motor for my project. There are two servos on ebay. Th First one is named Only "Towerpro micro 9g servo" and the second one that is cheaper is named as a "Towerpro 9g Digital servo".
The Links are:

Servo1: http://www.ebay.in/itm/TowerPro-SG90-9g-Mini-Servo-9-gram-Servo-RC-Robotics-/201386256243?hash=item2ee38e6773

Servo2: http://www.ebay.in/itm/251928442829?aff_source=Sok-Goog

My Problem is that I am confused with the name "Digital Servo". Its cheaper but I a afraid that will it work as normal.
Please help me.

Are both the same product, but with a different name?

Servos are digital by definition.  All you have there is two sellers that are selling the same product, but they are describing them slightly differently.  They are both SG90 servos. They are both digital (they require a digital PWM signal to control them, hence they are digital).

However, here's a little hint: Add the postage costs on to the cost of the servo - you'll see there's not that much difference in price - only 3 rupees between them.  That's about ¢5 or 3p.


What is the rise time of an output pin of atmega328 changing its state? I've already searched a lot and didn't found the answer. Also, I don't have an o'scope. Anyone can help me?

Last time I measured on a circuit (it was an i2c network master and with a 2560), it was about 0.3us, so that gives you a high value for that. Also, I believe it cannot be faster than one/half of a CPU cycle which takes: 1/(16E6)=62.5ns/2 = 31.25ns, so here's the lower boundary.

And there you got a possible range.

Then the rise time will definitely depend on the configuration of the circuit. It might be less or more depending on pull ups, capacitance attached at the pin out exit. It might also depend on the configuration of the pin (PWM? Internal Pull-up?…)

Finally, I believe there should some nominal values given in the datasheet.

Edit: Useful knowledge from the datasheet, but there's no definitive answer for any pin:

P311: 29.4.3 External Clock Drive

| Symbol | Parameter | Min | Max   | Min | Max   | Min | Max   |
| ------ | --------- | --- | ----- | --- | ---   | --- | ----- |
| tCLCH  | Rise Time |     | 2.0µs |     | 1.6µs |     | 0.5µs |

P313: 29.6 SPI Timing Characteristics

| Description    | Mode      | Min | Typ   | Max    |
| -------------- | --------- | --- | ----- | ------ |
| Rise/Fall time | Master    |     | 3.6ns |        |
| Rise/Fall time | Slave     |     |       | 1600ns |

P315: 29.7 Two-wire Serial Interface Characteristics

| Symbol | Parameter                      | Condition | Min        | Max   |
| ------ | ------------------------------ | --------- | ---------- | ----- |
| tr     | Rise Time for both SDA and SCL |           | 20 + 0.1Cb | 300ns |

HTH


Can i create a function inside of void setup()? Can i create a function inside of void setup()
to recall in loop() function

No. You do not create functions within functions.

You can create a function, and then call it both from setup() and loop() if you so wish.


Run two Loops Simultaneously on Arduino I am not able to combine the below two sketches. What I require is to either run both the loops together or find a way to run both the functions inside a single loop.

Sketch 1

#include <SevSeg.h>
#include <DS1307RTC.h>
#include <Time.h>
#include <TimeLib.h>
#include <Wire.h>

// Create an instance of the object
SevSeg sevseg;
bool militaryTime = false; // true for 24 hour clock

void setup() {
  byte numDigits = 4;
  byte digitPins[] = {2, 3, 4, 5};
  byte segmentPins[] = {6, 7, 8, 9, 10, 11, 12, 13};
  bool resistorsOnSegments = false; // 'false' means resistors are on digit pins
  byte hardwareConfig = COMMON_ANODE; // See README.md for options
  bool updateWithDelays = false; // Default. Recommended
  bool leadingZeros = true; // Use 'true' if you'd like to keep the leading zeros

  sevseg.begin(hardwareConfig, numDigits, digitPins, segmentPins, resistorsOnSegments, updateWithDelays, leadingZeros);
  sevseg.setBrightness(90);
}

void loop() {
  tmElements_t tm;
  int time;
  int dot;

  if (RTC.read(tm)) {
    time = tm.Hour * 100;
    if (time > 1200 && militaryTime == false) {
      time = time - 1200;
    }
    if (time == 0 && militaryTime == false) {
      time = 1200;
    }
    time += tm.Minute;
  }

  if ((tm.Second % 2) == 0) {
    dot = 4;
  } else {
    dot = 2;
  }

  //Produce an output on the display
  sevseg.refreshDisplay();
  sevseg.setNumber(time, dot);
}

Sketch 2

// Change this to the output pin you are using
#define TICK_PIN A0

void setup()
{
  pinMode(TICK_PIN,OUTPUT);
  while (1) {
    tone(TICK_PIN,1000,2);
    delay(1000);
  }
}

void loop()
{
}

Basically you need to get rid of the delay and any other blocking loops. Here is a way to do it.

Define this variable globally.

unsigned long lastTime = 0;

Then in your first loop, add the following code either to the beginning or the end:

if (millis() - lastTime >= 1000 || !lastTime) {
    lastTime = millis();
    tone(TICK_PIN,1000,2);
}


Console monitor on different wifi network I have a Yun doing data logging. It runs nicely and when I am on the same wifi network I can use the Console Monitor to watch what it is doing in more detail. However, my arduino is deployed far from me so it generally isn't possible to get on the same wifi network to monitor the console.

Is there a way to monitor the console from a different wifi network?

The Yun is just an ordinary network device.  However, the tools you are provided with use a system called mDNS to find the Yun.  That only works across the same local subnet that you are on.

If the Yun is on a different subnet then you will have to (assuming the routing between subnets is working fine) do it manually by knowing the IP address of your Yun.  Use that IP address in place of "arduino.local" or whatever your Yun is called.


How to send Arduino Yún Post Request to localhost? I've been trying to send data from my Arduino Yun to a local server using XAMPP. My code is shown below. In the serial monitor of the Arduino Yún, it shows connected and prints the data string, but in the server nothing is showing up. I don't know what's wrong. Maybe this doesn't work on a localhost? Any help would be much appreciated.

I've updated the Arduino code from something I found here.

send_data_ws.ino

#include <Bridge.h>
#include <Console.h>
#include <FileIO.h>
#include <HttpClient.h>
#include <Mailbox.h>
#include <Process.h>
#include <YunClient.h>

IPAddress server(192,168,1,200);
YunClient client;

String parametri="";
int x1,x2,x3;

void setup() {
  Bridge.begin();
  Serial.begin(9600);
  pinMode(A0,INPUT);
  pinMode(A1,INPUT);
  pinMode(A2,INPUT);
  String parametri ="";
  delay(2500);
  Serial.println("connecting...");
  x1 = analogRead(A0);
  x2 = analogRead(A1);
  x3 = analogRead(A2);
  if (client.connect(server, 80)) {
    Serial.println("connected");
    delay(2500);
    parametri="x1="+String(x1)+"&x2="+String(x2)+"&x3="+String(x3);
    client.println("POST /arduino/index.php HTTP/1.1");
    client.print("Content-length:");
    client.println(parametri.length());
    Serial.println(parametri.length());
    Serial.println(parametri);
    client.println("Connection: Close");
    client.println("Host:192.168.1.200");
    client.println("Content-Type: application/x-www-form-urlencoded");
    client.println();
    client.println(parametri);
 } else {
   Serial.println("connection failed");
 }
}

void loop() {
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }
  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
    for(;;);
  }
}

index.php

<?php
echo 'running....';
if ($_SERVER["REQUEST_METHOD"] == "POST"){
    $x1 = $_POST['x1'];
    $y1 = $_POST['x2'];
    $z1 = $_POST['x3'];
    echo 'x1: ' . $x1 . '
x2: ' . $x2 . '
x3:' . $x3 . '
';
}
?>

The Serial Monitor shows the PHP code using client.read() and as you can see it displays the data I sent to the PHP file, but in my server nothing shows up, only the running.... line shows up.

There needs to be an empty line between HTTP headers and data.

You need to end the Content-Length header line with

client.println(data.length());

so that the client.println(); inserts an empty line.


setup() resets from loop, when I add parameters to http get `?identity=%2B0123456789&identityType=1` I am trying to call a HTTP GET using my Arduino via SIM900A.

When I run the commands manually via the USB port, I am able to get the commands to run. Now, when I put the same sequence on arduino, the setup() is called repeatedly after the sendATcommand(httpAuthCommand, "OK", 2000);. Looks like a reset issue.

I read, this link to put all my code into loop to avoid the setup() reset issue. But seems like this is did not fix the issue.

I have debugged it to this one change.

This Works

char httpAuthCommand[] = "AT+HTTPPARA=\"URL\",\"http://www.m2msupport.net/m2msupport/http_get_test.php\"" ;

This Does Not work

char httpAuthCommand[] = "AT+HTTPPARA=\"URL\",\"http://1.1.1.1:8080/mytomcatservice/mypath/mycommand/Request?identity=%2B1234567890&identityType=1\"" ;

I debugged this a bit more, it does not work when I add ?identity=%2B0123456789&identityType=1 to the httpAuthCommand. Something crazy while sending parameters ??

In loop()

sendATcommand(httpAuthCommand, "OK", 2000);

sendATcommand method

int8_t sendATcommand(char* ATcommand, char* expected_answer, unsigned int timeout){

    uint8_t x=0,  answer=0;
    char response[100];
    unsigned long previous;
    memset(response, '\0', 100);    // Initialice the string
    delay(100);
    while( Serial.available() > 0) Serial.read();    // Clean the input buffer
    Serial.println(ATcommand);    // Send the AT command
    x = 0;
    previous = millis();
    // this loop waits for the answer
    do{
        // if there are data in the UART input buffer, reads it and checks for the asnwer
        if(Serial.available() != 0){
            response[x] = Serial.read();
            x++;
            // check if the desired answer is in the response of the module
            if (strstr(response, expected_answer) != NULL)
            {
                answer = 1;
            }
        }
    // Waits for the asnwer with time out
    }while((answer == 0) && ((millis() - previous) < timeout));

    return answer;
}

Raw commands work on Chrome

  http://www.m2msupport.net/m2msupport/http_get_test.php

  http://1.1.1.1:8080/mytomcatservice/mypath/mycommand/Request?identity=%2B918177900460&identityType=1

My Guess

I am missing some escape sequence characters in the command (especially in the parameters section ?identity=%2B0123456789&identityType=1).

"Something crazy while sending parameters ??"

Possibly your power supply is to weak so 5V drops low and the processor resets when the transmitter sends a message.


Sending multiple data with SPI interface monitored by an Osciloscope I have multiple 32-bit data stored in an array, and I want to sequentially send them by SPI interface. I want to check that my code is correctly sending data by SPI interface, so I upload the code and connect my Linkit7697 to an oscilloscope.
The expecting waveform is like this:

But it turns out to be like this:

It seems that all data are composited together in every 32 bits.
What's wrong? Any idea?
Here is my code:
#include <SPI.h>

#define SPI_MOSI (11)
#define SPI_MISO (12)
#define SPI_CS (10)
#define SPI_CLK (13)

uint32_t test[]={
  0xF0000000,   //11110000000000000000000000000000
  0x00F00000,   //00000000111100000000000000000000
  0x0000F000,   //00000000000000001111000000000000
  0x0000000F    //00000000000000000000000000001111
  };

int i = 0;

void setup() {
  digitalWrite(SPI_CS,HIGH); //Set slave select to high, linkit7697 is Master
  SPI.begin();
  SPI.beginTransaction(SPISettings(20000000,MSBFIRST,SPI_MODE0 ));

}

void loop() {

  for (i = 0; i < 4; i++){
    digitalWrite(SPI_CS,LOW);
    SPI.transfer(&test[i],4);
    digitalWrite(SPI_CS, HIGH);

  }

}

SPI.transfer(&test[i],4);

The SPI.transfer() transmit one byte each time and therefore expecting a pointer to a byte (i.e. uint8_t) while you are passing in an address of an uint32_t. What you need to do is to cast the address of uint32_t into a pointer of uint8_t before passing it into the SPI.transfer.
uint8_t *ptr = (uint8_t *) &test;

SPI.beginTransaction(SPISettings(20000000,MSBFIRST,SPI_MODE0 ));
digitalWrite(SPI_CS,LOW);
for (i = 0; i < sizeof(test); i++) {
  SPI.transfer(*ptr++, 4);
}
digitalWrite(SPI_CS, HIGH);
SPI.endTransaction();

Please also note that Arduino is a little endian machine, so if you have a data as 0x41424344, the first byte get transmitted will be 0x44.
One more thing, it is always good to call SPI.endTransaction(), it free up the SPI bus to allow other SPI devices to use the data bus.


How to send and receive multiple integer values through serial comm for Arduino Micro and HC05 bluetooth? I need to send gyroscope values and a voice command flag and counter with a start and end marker through serial in the format <2,4,5,6> through Arduino Software serial using the HC05 Bluetooth module between Arduino Micro boards. I can send values in the struct format. But it seems that the order of the struct gets changed after a few seconds of receiving on the other side. How can I send these values in the mentioned format? I am new to this. Please help me out. It would also help if I could get suggestions on how to receive and parse this data of this format in the correct order/way.

Try Google Protobuf it's really awsome. I use it every time when I connect C# app to STM but it can be used in this case as well. U use Protobuf to encode your message and COBS do remove zeros from message so you can slap it on the end to know when the packet ends


my LM35 temperature sensor gives weird measurements, Board: esp32

I know my wiring is correct because I get data from the sensor, but the data is a bit weird.

At 22 celcius I get 140, even though if I do the voltage calculation (* 0.473372) it still doesn't work.

the number 0.473372... comes from taking the voltage 4.7v / 1024 * 1000 / 10

My code:

 Serial.print("temp: ");
 float temp = (analogRead(A13) * 0.473372781065088);
 Serial.println(temp);
 delay(2000);

Any answers?

ok, the problem is that i used to the wrong voltage conversion, just use:

RawValue = analogRead("your analog input pin");
Voltage = (RawValue / 2048.0) * 3300;
Serial.println(Voltage);

this should print the tempeture in celcious


Detect and stream if a chair is occupied I am planning to build a device able to detect and tell a server via Wi-Fi if a chair is occupied. How would you do it? And how cheap do you think the device could be?

For a soft seat you could sense occupancy with an LED and photo-sensor at opposite ends of a short somewhat flexible tube that gets flexed when the cushion compresses, interrupting the light. That or a microswitch would have to be the cheapest means of sensing.

Getting from there to the server depends a little on how much work you're willing to do, from rolling your own micro-controller+WiFi PCB to purchasing off the shelf parts, which may in turn, depend on whether you need to monitor one chair or a whole auditorium.


How to allow cross-domain requests on ESP8266WebServer I am using a Raspberry Pi running Chrome (handling the user interface) and connecting via ajax to an Arduino D1 compatible using the IP address as follows:

    $.ajax({
        type: "GET",
        url: "http://10.1.1.100/myfunc?id=5",
        error:  function(jqXHR, exception, response) {
                console.log(exception, response);

        etc...

I recently started getting this error (wonder why it didn't happen for the last two years):

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://10.1.1.100/myfunc?n=1. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

I tried various things including setting the browser (Chrome) to --disable-web-security and various suggestions, here and here (and many more) but I can't seem to get it to work. Currently, I have:

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
ESP8266WebServer server(80);

void handleRoot() {
  server.send(200, "text/plain", "Root of WebServer!");
}

void setup() {
IPAddress ip(10.1.1.100);
IPAddress gateway(10.1.1.1);
IPAddress subnet(...);
WiFi.begin(ssid, password);
WiFi.config(ip, gateway, subnet);
  // put your setup code here, to run once:
  WiFi.begin(ssid, password);
  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
  }

  server.on("/", handleRoot);

  server.on("/myfunc", [](){
    String message = "";
    message += "URI: ";
    message += server.uri();
    message += "\nMethod: ";
    message += (server.method() == HTTP_GET)?"GET":"POST";
    message += "\nArguments: ";
    message += server.args();
    message += "\n";
    for (uint8_t i=0; i<server.args(); i++){
      message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
    }
      String num = server.arg(0);

    server.send(200, "text/plain", message);
 });
  server.on("/myfunc", HTTP_OPTIONS, []() {
    server.sendHeader("Access-Control-Allow-Origin","*")
    server.send(204);
 });

  server.onNotFound(handleNotFound);
  server.begin();
}

void loop() {
  delay(1000);
  ...
  server.handleClient();
}

void handleNotFound(){
  String message = "Error!";
  server.send(404, "text/plain", message);
}

So what am I doing wrong? Also, one complication that might crop up later is that the domain from where I am calling this in ajax is https and from what I understand https and http are not compatible with cross-domain requests.

Any help is appreciated!

Add the CORS header to every response, not only for 'preflight' OPTIONS request. The OPTIONS support is optional, but the response returning the 'shared resource' must contain the CORS header

"Access-Control-Allow-Origin: *"


Streaming integer data from Arduino to Java, integer greater than 0xFF I need to send how many milliseconds elapsed since the beginning of the time the arduino runs to java using Serial.write(). However, the largest integer that I can throw in there is 255, naturally since the largest 1 byte value we can send is 0xFF.
But if we have an integer like 6000 miliseconds that I want to send into java, how can I do this? I was initially thinking of just checking if the number is greater than 255 then bit shift it by 4 to the left then doing number<<4 & 0xFF00 and also writing (number<<4)>>8 &0xFF
But

that doesn't work for numbers really large and
I believe when I stream these int values into Java they get read as characters...

how do I fix this?
EDIT
I've created a second version as the following
void sendData(int a ){
  while(a>0){
    Serial.write(a&255);
    a = a>>8;
  }
}

on the java side I have to somehow multiply the correct x for 16^(x) to the value that we receive since everything is received backwards I'm not sure if this is the best way to go since we don't necessarily know how many bytes that we'll receive

I'm assuming you will be using the Arduino millis() function for keeping time. The output of the millis() function in the Arduino environment is a 32-bit unsigned integer*.
A 32-bit integer can be split into 4 x 8-bit bytes. To keep things simple you could program the Java receiving side to always expect 4 bytes (or whatever amount you need, see *). Assuming 32 bits is enough, you could use the following:
void sendData (uint32_t uptime) {
    int i;
    for (i = 0; i < 4; i++) {
        Serial.write (uptime & 255);
        uptime = uptime >> 8;
    }
}

On the Java side, you would receive the lowest order byte first, and you could reconstruct the 32-bit value by taking the first received 8-bit value, adding the second value shifted left by 8 bits (=multiplied by 256), adding the third value shifted left by 16 bits (=multiplied by 65536) and adding the fourth value shifted left by 24 bits (=multiplied by 16777216). Java is not my strong point so I will leave that to you.
BTW, is there a particular reason you have to use Serial.write()? It would be much easier to just write the value as a string with Serial.println().
*After 2^32 milliseconds (a little under 50 days of uptime) the 32-bit counter that feeds the millis() function will wrap around to 0. You could keep the amount of times that the timer has overflowed in a separate (integer) variable and make that (i.e. bytes 5 and onward) part of your output.


Seamlessly loop through LED's - Shift Register I am using the following code to create a snake-like affect (3 LED's wide) moving through 24 LED's using 3 shift registers:

 for(int i = 0; i < 27; i++){
    setRegisterPin(i, HIGH);
    writeRegisters();
    if(i >= 3){
     setRegisterPin(i-LEDLength, LOW);
     writeRegisters();
    }
    delay(100);
  }//end for

The problem with this is that the snake has to completely end before it starts again, instead of looking like one continuous snake going in circles.

So when the three LED's get to the end I want it to immediately begin to light the beginning again. If 2 are lit at the end then 1 should be lit at the start, etc. Like this pattern:

You mean something like this? (untested):

void loop() {
  // use static or global variables to remember positions (these are initialized only once):
  static uint8_t hi_pos = 0;  // where HIGH should be set
  static uint8_t lo_pos = 21; // where LOW should be set

  setRegisterPin(hi_pos, HIGH); // turn on led in head
  setRegisterPin(lo_pos, LOW);  // turn off led in tail
  writeRegisters();             // update registers

  // ensure it won't overflow:
  if (++hi_pos == 24) hi_pos = 0;
  if (++lo_pos == 24) lo_pos = 0;

  // or:  hi_pos = (hi_pos+1) % 24;  // but divisions are slower on AVR

  delay(100);
}

It will go in sequence:

ON  OFF
 0   21
 1   22
 2   23
 3    0
 4    1
...
22   19
23   20
0    21
...

forever


Arduino Uno WiFi - How to disable WiFi? I'm using Arduino Uno Wifi. I made my Arduino to get connected with my local network based on http://www.arduino.org/learning/getting-started/getting-started-with-arduino-uno-wifi

Now I would like to disable it and work with USB serial communication to upload sketches. But now I'm unable to upload sketches even if I select the serial port. I'm getting an AVRDUDE : seropen() Access is disabled error. I could perfectly do uploading if I select the networked port of the same Arduino.

Can I know why ?

The reason why "Arduino WiFi Dev Ed" USB upload sometimes doesn't work, is the esp8266 connected to UART of Atmega for the OTA upload. If esp8266 doesn't boot, it doesn't set pin 4 to disconnect from Atmega UART and the connection to UART stays and disturbs the upload from IDE.

The esp8266 hangs sometimes, because it has pin 2 floating on this board, but there is a trace and a soldering point on the bottom of the board for pin 2. If it is touched or otherwise grounded the esp8266 doesn't boot until the potential on the pin rises.

More about Uno WiFi Dev Ed hardware here.


arduino is skipping the if statement Hi guys I am new to this language and i just tested the code to control a servo motor
Can anybody help me please ? here is the code

void setup() {

  servo_test.attach(3);
  pinMode(9, INPUT);

}

void loop() {

 if ( digitalRead (9 == HIGH)) {

   for(angle = 0; angle < 180; angle += 5)    to 180 degrees
  {
    servo_test.write(angle);
    delay(5);
  }

  delay(4000);
  for(angle = 180; angle>=1; angle-=5)      to 0 degrees
  {
    servo_test.write(angle);               specified angle
    delay(5);
  }

    delay(4000);
}

}

It is just like the arduino completely ignore the if statement and start the loop wheter pin 9 is in high or low state  even if  i wire it directly to gnd

In your code this line:

 if ( digitalRead (9 == HIGH)) {

...is likely passing the function "digitalRead()" the value zero as "9 == HIGH" is likely false.

Likely what you want to do is check if the value returned by the function "digitalRead()" is high.  Try:

 if ( digitalRead (9) == HIGH) {

...instead.


What is the difference between the revisions of the Arduino Uno board? There are three different revisions of the Arduino Uno. What changed in each revision?

Here is a summary from the official site:

Revision 2 of the Uno board has a resistor pulling the 8U2 HWB line to
ground, making it easier to put into DFU mode.
Revision 3 of the board has the following new features:

1.0 pinout: added SDA and SCL pins that are near to the AREF pin and two other new pins placed near to the RESET pin, the IOREF that
allow the shields to adapt to the voltage provided from the board. In
future, shields will be compatible with both the board that uses the
AVR, which operates with 5V and with the Arduino Due that operates
with 3.3V. The second one is a not connected pin, that is reserved for
future purposes.
Stronger RESET circuit.
Atmega 16U2 replace the 8U2.

A more detailed list of changes can be found here.
R2:

The rotation of the ATMEGA8U2 (the little chip near the USB port) was changed by 45 degrees.

Four solder pads (JP2) were added, connecting to pins PB4 to PB7 of the USB ATMEGA."

Instead of R1's solder pads, R2 adds header pins to the USB ATMEGA ICSP.

An LED connected to pin 13 was added. It turns on when pin 13 is HIGH, off when LOW.

The main microchip was changed from an ATmega168 to an ATmega328.

A resistor was added between the DTR (HWB) line and the ATMEGA PD7 pin.

R3:

The rotation of the ATMEGA8U2 was changed back by 45 degrees.
The ATMEGA8U2 was changed to an ATMEGA16U2.
A diode was added, wired from +5vdc to the reset pin, cathode to +5vdc.

The 8 pin connector that contains Arduino pins 8 was changed to 13, GND and AREF for a 10 pin connector. The extra 2 pins are connected to AD4/SDA and AD5/SCL. Also, the 6 pin connector that has the reset pin connected to it changed to an 8 pin connector. One of the new pins on this header is the IOREF pin that allows shields connected to the board to adapt to the voltage of the board. The second pin is not connected and reserved for future use.


Error on Uploading Program to ESP8266 via Foca v2.2 (USB to TTL Adapter) BACKGROUND

To test the capability of uploading program to ESP8266,  I use an empty program with only a blank setup function and a blank loop function. The result showed me that there are a espcomm_sync error and a espcomm_open error. Any idea to solve this problem?

HARDWARE

PIN CONNECTION

  Foca v2.2 <-> ESP8266
        TXD <-> RXD
        RXD <-> TXD
        DTR <-> RST

Arduino UNO <-> ESP8266
        GND <-> GND
       3.3V <-> Vcc

PIN DIAGRAMS

Foca v2.2

ESP8266

ON LINUX UBUNTU 15.04

ON WINDOWS 10

REFERENCE

Bring IoT to Arduino, together [Getting Started] - http://www.arduinesp.com/getting-started

by the comments I think you are not understanding correctly how to connect Reset and GPIO_0 of ESP. To set esp-01 into flash mode (to program) you need to set GPIO_0 Low (GND) and then also apply Low on RST ESP pin.
To debug the things and be certain that there is no hardware problem let just start by doing these connections:

Foca v2.2 <-> ESP =1
      TXD <-> RXD
      RXD <-> TXD
      GND <-> GND
  Arduino <-> ESP 01
     3.3V <-> 3.3V
     3.3V <-> CH_PD
     GND  <-> GND

Now, with a wire, connect GPIO_0 to ground. With another wire, briefly connect RST of the ground to make ESP reset. You should be now in flash mode. Remove the connection on GPIO_0 and make it float. Now upload the code.

Note: this is basically the option C on the link you provide. If you have some buttons you can make it too:

(source: arduinesp.com)

Now, does the code upload in Arduino IDE?

If the answer is still no, try to add a small capacitor between 3.3v and ground.

If the answer is yes, now you can move on and try the other options described in the link you provide. I recommend using the option A:

(source: arduinesp.com)

Any generic npn transistor should work


Does Keyboard.begin() and Keyboard.end() make my code slower? I'm making an IR Macro keyboard, and about 10% of the code is dedicated to the Keyboard commands, would having Keyboard.begin() and Keyboard.end() in the method responsible for typing make any difference to the speed or size?
My code:

void decodeCode(){ // send the macros.
  int pos = 0;
  for(int i = 0; i<output.length(); i++){
    if(output.charAt(i) == '$' && i!=output.length()-1){ //the $ is a symbol for "$pecial" characters
      i++;
      specialDecodeChar(output.charAt(i));
    }
    else if(output.charAt(i) == '%'){
      Keyboard.releaseAll();
    }
    else{
      Keyboard.press(output.charAt(i));
    }
  }
  Keyboard.releaseAll();
}

I currently have Keyboard.begin() in setup().

The Keyboard::begin() and Keyboard::end() functions,  if you actually look at the code are empty functions. They do nothing.

In theory the compiler should just optimise them out.


Stop servo when enter 0 I am trying to stop servo motor from rotating when I enter 0 in serial. The code is below. Can someone please help?

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards
int state;
int pos = 0;    // variable to store the servo position

void setup()
{
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  Serial.begin (9600);
}

void loop()
{
  if (Serial.available () > 0)
  {
    state = Serial.read ();
    if (state == '1')
    {
      for (pos = 0; pos <= 180; pos += 1)
      {
        myservo.write(pos);              // tell servo to go to position in variable 'pos'
        delay(15);
      }
      for (pos = 180; pos >= 0; pos -= 1)
      {
        myservo.write(pos);              // tell servo to go to position in variable 'pos'
        delay(15);      // waits 15ms for the servo to reach the position
      }
      if (Serial.available () > 0)
      {
        state = Serial.read ();
        if (state == '0')
        {
          myservo.write ('90');
          delay (300);
        }
      }
    }
  }
}

From the code you posted it looks like you have the right idea but you've nested the 'IF' statements causing the check for '0' to only happen if you send two bytes and it will only go to 90deg when you send '10'.  The loop section should look more like:

if(Serial.available()){
    state = Serial.read();
    if(state == '1'){
           Make motor move;
    }else if(state == '0'){
           Make motor stop;
    }//end of elseif
}//end of if


Serial Communication over Desktop to Arduino I have a USB 2 Serial adapter and the device is working fine. I see the device perfectly configured in my System.

I have connected the TX0 pin of Arduino to DB 2 pin (read pin) of the adapter. Below is my Arduino code:

int i = 0;
void setup()
{
  Serial.begin(9600);
}

void loop()
{
  for(i=0;i<6;i++)
  {
  Serial.write('H');
  delay(100);
  }
}

But when I try to read thru terminal software of data received at my COM port I see some junk character incoming. I am pretty sure that I am using same baud rate / flow setting both side. Why am I facing this issue - do I need to connect any other pins also as I just need to receive data at system side?

I have a USB 2 Serial adapter...I have connected the TX0 pin of Arduino to DB 2 pin (read pin) of the adapter.

You must not connect Arduino pins directly to a D-SUB connector of a USB-Serial adapter, as those connectors traditionally carry higher voltage, opposite sense RS232 signals.

The voltage is too high, and likely to cause damage to your Arduino's processor
The signal is inverted in sense from the logic-level signaling used by your Arduino's processor.

If you actually needed to make this connection, you would need to either use a "logic level" USB serial adapter (sometimes informally called a USB-TTL adapter).  These terminate in various types of connections such as bare wires or header pins/sockets - but basically never in an D-SUB connector.  Or you can use an inverting line driver and receiver such as the MAX2232 type devices, or even an old 1488/1489 pair.

But it's not clear that you should be doing this at all - an Arduino Mega already has a USB-serial converter onboard - that is the interface you use to program it, and it would ordinarily be simplest to use that for runtime communication as well.


DFplayer, Play sound when pin is high I have a code here, from DFmini player. I have a tactile switch. when I press it on and release it will play a sound. My question is that when I press the tactile but not release it so I want it still play the same sound.
But while the tactile switch is pressed down it keeps repeating the same sound. I want it to play just for once while the tactile button is still pressed down.
//#include <SoftwareSerial.h>   //If we use other pins than D0 adn D1 for TX and RX for the music player
#include <DFMiniMp3.h>          //Downlaod here: https://electronoobs.com/eng_arduino_DFPlayer_Mini_Mp3_by_Makuna.php

int sw1 = 3;
int sw2 = 4;
int sw3 = 5;
int sw4 = 6;
int sw5 = 7;
int sw6 = 8;
class Mp3Notify
{
public:
  static void OnError(uint16_t errorCode)
  {
    // see DfMp3_Error for code meaning
    Serial.println();
    Serial.print("Com Error ");
    Serial.println(errorCode);
  }

  static void OnPlayFinished(uint16_t globalTrack)
  {
    Serial.println();
    Serial.print("Play finished for #");
    Serial.println(globalTrack);
  }

  static void OnCardOnline(uint16_t code)
  {
    Serial.println();
    Serial.print("Card online ");
    Serial.println(code);
  }

  static void OnCardInserted(uint16_t code)
  {
    Serial.println();
    Serial.print("Card inserted ");
    Serial.println(code);
  }

  static void OnCardRemoved(uint16_t code)
  {
    Serial.println();
    Serial.print("Card removed ");
    Serial.println(code);
  }
};

DFMiniMp3<HardwareSerial, Mp3Notify> mp3(Serial);   //Create the UART connection to the module

void setup()
{
  //3 push buttons with pullups
  pinMode(sw1,INPUT);                        //Define each button as input with pullup
  pinMode(sw2,INPUT);
  pinMode(sw3,INPUT);
  pinMode(sw4,INPUT);
  pinMode(sw5,INPUT);
  pinMode(sw6,INPUT);
  digitalWrite (sw1, HIGH); //12 Votls supply set to off state
  digitalWrite (sw2, HIGH); //5 Votls supply set to off state
  digitalWrite (sw3, HIGH); //3 Votls supply set to off state
  digitalWrite (sw4, HIGH); //Ajustable Votls supply set to off state
  digitalWrite (sw5, HIGH); //3 Votls supply set to off state
  digitalWrite (sw6, HIGH); //Ajustable Votls supply set to off state
  Serial.begin(9600);
  mp3.begin();                                      //Start communication with the DFplayer module
  uint16_t volume = mp3.getVolume();                //Get actual volume
  mp3.setVolume(30);                                //Set new volum (max is 30)
  uint16_t count = mp3.getTotalTrackCount();        //Get the total tracks on the SD card in case we want to sue this later...
}

//just a fucntion that we use to create delays in "ms"
//without using the delay() function
void waitMilliseconds(uint16_t msWait)
{
  uint32_t start = millis();

  while ((millis() - start) < msWait)
  {
    // calling mp3.loop() periodically allows for notifications
    // to be handled without interrupts
    mp3.loop();
    delay(1);
  }
}

void loop()
{
  if(!digitalRead(sw1))
  {
      mp3.playMp3FolderTrack(1);  // Play audio track 0001
      waitMilliseconds(1000);     // 1s of delay
  }

  if(!digitalRead(sw2))
  {
      mp3.playMp3FolderTrack(2);  // Play audio track 0002
      waitMilliseconds(1000);     // 1s of delay
  }

  if(!digitalRead(sw3))
  {
      mp3.playMp3FolderTrack(3);  // Play audio track 0003
      waitMilliseconds(1000);     // 1s of delay;
  }

  if(!digitalRead(sw4))
  {
      mp3.playMp3FolderTrack(4);  // Play audio track 0001
      waitMilliseconds(1000);     // 1s of delay
  }

  if(!digitalRead(sw5))
  {
      mp3.playMp3FolderTrack(5);  // Play audio track 0002
      waitMilliseconds(1000);     // 1s of delay
  }

  if(!digitalRead(sw6))
  {
      mp3.playMp3FolderTrack(6);  // Play audio track 0003
      waitMilliseconds(1000);     // 1s of delay;
  }

}//end of void

BOUNCE 2
Basically, the mechanical part of buttons and switches vibrate slightly when closed or opened causing multiple undesired false states (similar to noise). This library filters out these undesired state changes. More about debouncing:
John Errington's Experiments with an Arduino : Using digital inputs: Switch bounce and solutions to it
Wikipedia article : http://en.wikipedia.org/wiki/Debounce#Contact_bounce
See the bottom of this page for a basic usage example and the "examples" folder for more.
The library is composed of three classes:
Debouncer : The code that does the actual debouncing. Only advanced users should play with this class.
Bounce : This is the general use library. It links the Debouncer to a hardware pin on your board.
Button : A special version of Bounce for buttons that are pressed.
https://github.com/thomasfredericks/Bounce2


Setting a pointer to NULL in Arduino library - error: ‘NULL’ was not declared in this scope I am writing my own library for using with my Arduino. In my code, if I set a pointer I have declared to NULL, such as

int *ptr=NULL;

I get the error

error: ‘NULL’ was not declared in this scope

I need to initialize it to NULL as I am using pointers to implement a list.

If I use NULL directly in the program in the IDE, I do not get this error. This seems to be happening only when it is a part of the library code.

How do I correct this? Is there any alternative keyword to use? Or do I have to include some library?

Thank you.

You should make sure your header includes the stddef.h header, which holds all these standard definitions (hence its name):

#include <stddef.h>


How do I view Serial Output on an Android Device? Within the Arduino IDE Serial.* output can be viewed with Tools / Serial Monitor.  How can I view Serial.* output on an Android?  As a concrete example, how can I view the output from Examples / Communication / ASCIITable?

These steps will allow your Android device to function as an Arduino Terminal.

Download a Serial Terminal app.  I'm using Android Hyperterminal, English version.
Attach an OTG ("On The Go") cable to your Android device.
Attach your Arduino to the OTG using your regular USB cable.
Make sure the terminal program is set to the same baud rate as your sketch.
Run the terminal App and select the USB port.


Input audio from jack to Arduino, and output by I've never used Arduino but I know a few of its utilities.

I want to input audio from a Jack cable (analog) and be able to send it via Bluetooth, or Wi-Fi, or USB to an Android Phone and being able to print the values (from 0 to 1).

I'm looking for tutorials but I just find the way to make the input but not the output.

Which one would you recommend me of Bluetooth, Wi-Fi and USB?

Thanks.

The simplest solution: it really depends. There are a couple of things to consider:

Bluetooth would probably be the least professional to impliment. The easiest way to do this is with an app. You can impliment it into your application with this:

  Let your own Android application receive data from Arduino by listening to the "primavera.arduino.intent.action.DATA_RECEIVED" intent. This intent will contain the "primavera.arduino.intent.extra.DATA" byte array with the received data. Call getByteArrayExtra("primavera.arduino.intent.extra.DATA") to retrieve the data. Send data to Arduino from your application by broadcasting an intent with action "primavera.arduino.intent.action.SEND_DATA". Add the data to be sent as byte array extra "primavera.arduino.intent.extra.DATA".

Still, that's pretty unprofessional IMHO. There are probably other ways to do this, but Arduino Uno Communicator is the easiest by far that I've seen. The main advantage of Bluetooth is it works without a router and it's very cheap (as far as wireless). I can't remember if it's the HC4 or HC5 chip that is commonly available, but [one of those] can be picked up for around $6. Just connect via serial and issue AT commands.
WiFi would be the most professional. First of all, people hear Wifi and they think Ohh! Shiny! I'm going to buy it! That's just what I've observed in the past, but it may not always be true. WiFi can be done with the TL-WR703N router. This blog post outlines how you can even connect it directly to the Arduino. You can also use an ethernet shield (or equivalence, I've seen breakout ethernet boards built for ~$5). Either way, it's a great way to add 5V WiFi to your Arduino. The only disadvantage is cost and it only works if you're near a WiFi router. If those aren't disadvantages, go ahead with WiFi; it's a great product.
USB is only useful if you want:

Speed
Stability
Portability (i.e. no WiFi Router)

Speed can be eliminated as a need if you only send data every 300 ms or so, depending on what you're doing. For WiFi, it might be best to only go to a webpage when an even occurs (i.e. button pushed on Arduino). Bluetooth and WiFi are stable enough if you're over short distances (and you couldn't go a long way with wires, anyway), and there's not too much interference (don't try at a football game with 50K cell phones... granted, they will be on different bands if using cell service, but Bluetooth may be on).

As far as portability, for the price of an OTG cable for your phone, you'd be better off buying a Bluetooth module for a dollar extra.

Suggestion: go with WiFi unless you need the portability. Consider figuring out WPS so your users can connect to WiFi with a push of a button. I don't know if the TL-WR703N has support for WPS, via serial or not.

Forgot to mention: I don't know everything about your app, but WiFi might have too much latency/overhead for near-instant response. As far as wireless, Bluetooth would have much lower latency AFAIK. (As you can tell, there's no perfect solution here :-))


MIDI Keyboard control I am relatively new to Arduino and I am looking to implement a simple system that uses a MIDI keyboard to

(i) detect key presses (via MIDI messages) from the keyboard

(ii) store the information of the MIDI messages (note pressed, velocity)

(iii) Light up LEDS on the keyboard based on what key was pressed

I am currently in the planning stage and I am considering using an Arduino Mega. I have two issues I am not sure about:

(i) My keyboard only has a Male USB A to Male USB B connection with the former connecting to the computer and the latter to the keyboard. So far in my search, I have seen that all Arduino-MIDI projects require a 5 pin MIDI cable to interface with the Arduino using the circuit in this webpage (https://www.instructables.com/id/Send-and-Receive-MIDI-with-Arduino/). Is there any way to detect MIDI messages that does not require the additional circuit and just uses the USB cable?

(ii) Although in theory control of the LEDs should be easy in the program, I am concerned that the delays in the serial communication and hardware interrupts would make it difficult to simultaneously receive the MIDI messages and control the LEDs.

One way I thought of avoiding these problems is to use MATLAB MIDI package (https://uk.mathworks.com/help/audio/ug/midi-device-interface.html#mw_80dc54f4-867c-43c0-a159-e56ee62ec4ab) to interface with the MIDI device and use the MATLAB Arduino package to control the Arduino. I am not sure, however, if MATLAB is suboptimal compared to the standard Arduino IDE.

This is my first question in Arduino StackExchange (or any StackExchange site), so I appreciate the answers and feedback on my question.

Is there any way to detect MIDI messages that does not require the additional circuit and just uses the USB cable?

You could probably do it with a "USB Host Shield", though I have no experience of them and don't know if they can handle MIDI - you'll have to research this.

  Although in theory control of the LEDs should be easy in the program, I am concerned that the delays in the serial communication and hardware interrupts would make it difficult to simultaneously receive the MIDI messages and control the LEDs.

Highly unlikely. You'd have to be doing something very wrong to make it so slow to respond that you'd see any delay.

  I am not sure, however, if MATLAB is suboptimal compared to the standard Arduino IDE.

I cannot comment, I have never used MATLAB. If you don't use a USB Host Shield then you will certainly require something that runs on a PC to forward the MIDI information over serial.  Whether you create that in MATLAB or some other programming language is neither here nor there as far as the Arduino is concerned - you'll still need to program the Arduino itself, and that can be done in the IDE and still use MATLAB for the PC portion of your setup.


Is there any way to download a sketch from an Arduino? I made a sketch, but then I lost it. However, I uploaded it to the Arduino before losing it. Is there any way I can get it back?

It should be possible as long as the security bit isn't set. This question was asked on EE a while back.

Is it possible to extract code from an arduino board?

But you won't get the Arduino code you wrote back. The code is compiled into assembly and you'll have to convert that back to C yourself.


Capture GRAYSCALE image with ESP32 Cam For one of my projects, I would like to transfer a camera image with the best possible resolution and as many FPS as possible with the ESP32Cam.
For this I successfully used the code from
https://RandomNerdTutorials.com/esp32-cam-video-streaming-web-server-camera-home-assistant/
A grayscale image would be enough for further processing, if it allows a higher speed.
Problem is, if I set the format to PIXFORMAT_GRAYSCALE, the ESP only outputs "Camera capture failed".
Are there any other settings to do?

I just tried this with my ESP32Cam with no problems.  I would check that you are supplying enough power; I've definitely seen the 'Camera capture failed' when I had power issues.  Also, I would try a more recent tutorial on the ESP32Cam; the latest Expressif ESP32 Arduino libraries have AI Thinker ESP32Cam as a device choice.  I would try the CameraWebServer example in the ESP32 library and see if you still have the problem.


Unable to read text file from server I saw the Web client Example  , In the example, the server connection is initialized in setup(). But I want the server to update the text file every time. So, I need the server connection to be in loop().

But, it is not working. Where is the problem in my code.

#include <GSM.h>

#define PINNUMBER ""

// APN data
#define GPRS_APN       "GPRS_APN" // replace your GPRS APN
#define GPRS_LOGIN     "login"    // replace with your GPRS login
#define GPRS_PASSWORD  "password" // replace with your GPRS password

// initialize the library instance
GSMClient client;
GPRS gprs;
GSM gsmAccess;

// URL, path & port (for example: arduino.cc)
char server[] = "yourdomain.com";
char path[] = "/current.txt";

int port = 80; // port 80 is the default for HTTP

void setup() {
// initialize serial communications and wait for port to open:
Serial.begin(9600);
Serial.println("SMS connected");

// connection state
boolean notConnected = true;

// After starting the modem with GSM.begin()
// attach the shield to the GPRS network with the APN, login and password
while(notConnected) {
   if((gsmAccess.begin(PINNUMBER)==GSM_READY) &
    (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD)==GPRS_READY))
    notConnected = false;

else {
     Serial.println("Not connected");
     delay(1000);
    }
   }
Serial.println("GPRS connected...");
Serial.println(" Connecting to Server ");
}

void loop() {
if (client.connect(server, port)) {
  client.print("GET /current.txt");
  Serial.print("GET /current.txt");
  client.println(" HTTP/1.1");
  Serial.println(" HTTP/1.1");
  client.println("Host: www.yourdomain.com");
  Serial.println("Host: www.yourdomain.com");
  client.println("User-Agent: Arduino");
  Serial.println("User-Agent: Arduino");
  client.println("Accept: text/html");
  Serial.println("Accept: text/html");
  client.println("Connection: close");
  Serial.println("Connection: close");
  client.println();
  Serial.println();
  Serial.println("\nCOMPLETE!\n");
  //client.stop();

} else {
  Serial.println("connection failed");
  Serial.println("\n FAILED!\n");
}

if (client.available()) {
  char c = client.read();
  Serial.print(c);

} else {
  Serial.println();
  Serial.println("disconnecting.");
  client.stop();
}
}

Its working as long as the connection doesn't break or the server doesn't stall. We must wait till the response .

while (client.connected())
{
 while(client.available())
 {
 char ch = client.read();
 Serial.print(ch);
 }
}
 client.stop();


how to convert the following code into one using direct port manipulation Following is the program for scanning a keyboard for MIDI transfer.
At present the code works fine, but it could be faster.
I need to know how to use direct port manipulation inside the for loop.
boolean keypressed[6][6]; //for storing key states
int midinote[6][6] ={ 60 ,61 ,62 ,63 ,64 ,65
                 ,66 ,67 ,68 ,69 ,70 ,71
                 ,72 ,73 ,74 ,75 ,76 ,77
                 ,78 ,79 ,80 ,81 ,82 ,83
                 ,84 ,85 ,86 ,87 ,88 ,89
                 ,90 ,91 ,92 ,93 ,94 ,95  }; //code for various midi notes C3 to C6

void setup() {

   Serial.begin(38400);
   for(int i=0; i<6; i++){
      pinMode(i+2,OUTPUT);
      digitalWrite(i+8,HIGH);
   }
   for(int i=0; i<6; i++){
      pinMode(i+8,INPUT);
      digitalWrite(i+8,HIGH);
   }
   for(int i=0; i<6; i++){
      for(int j=0; j<6; j++){
          keypressed[i][j] = false;
          }
      }
   }
void loop() {

   for(int i=0; i<6; i++){
      digitalWrite(i+2, LOW);
      for(int j =0; j<6; j++){
         if ((digitalRead(j+8) == LOW) && !keypressed[i][j]){
            Serial.write(0x91);
            Serial.write(midinote[i][j]);
            Serial.write(127);
            keypressed[i][j] = true;
           }
         if ((digitalRead(j+8) == HIGH) && keypressed[i][j]){
            Serial.write(0x91);
            Serial.write(midinote[i][j]);
            Serial.write(0);
            keypressed[i][j] =false;
         }
      }
digitalWrite(i+2, HIGH);
   }

 }

It is better to use interrupts instead of pooling pins.
but this is related to your arduino controller.
what is you arduino core controller?
if you can select I prefer "Nano 33 IoT " which has 9 pins (2, 3, 9, 10, 11, 13, 15, A5, A7) available for interrupt.
this page may be usable:
https://playground.arduino.cc/Main/PinChangeInterrupt/


"Does not name a type" error with Serial.print I am getting an error that I have never seen before and don't know how to fix. Basically I am trying to print a string (stored in thermistor) to the serial monitor. When I run the code I get an error message that says: exit status 1
'Serial' does not name a type.

What can I do fix this error?

void setup() {
Serial.begin(9600);
pinMode(4, OUTPUT);
pinMode(6, OUTPUT);
pinMode(8, OUTPUT);

}

void loop() {

} <==== ERROR: loop() ENDS TOO EARLY
String heartMonitor = codeWrite(4, HIGH, LOW, HIGH);
String lilyPad = codeWrite(6, HIGH, LOW, LOW);
String thermistor = codeWrite(8, HIGH, HIGH, LOW);
Serial.println(thermistor);
delay(1000);

String codeWrite(int pin, char output1, char output2, char output3)
{
  digitalWrite(pin, output1);
  int A = digitalRead(pin);
  delay(1);
  digitalWrite(pin, output2);
  int B = digitalRead(pin);
  delay(1);
  digitalWrite(pin, output3);
  int C = digitalRead(pin);
  delay(11);
  String code = String(A) + String(B) + String(C);
  <==== ERROR: MISSING RETURN STATEMENT
}

If you move this code into loop(), the sketch will compile.

String heartMonitor = codeWrite(4, HIGH, LOW, HIGH);
String lilyPad = codeWrite(6, HIGH, LOW, LOW);
String thermistor = codeWrite(8, HIGH, HIGH, LOW);
Serial.println(thermistor);
delay(1000);

EDIT:

The sketch should look like this:

void setup() {
  Serial.begin(9600);
  pinMode(4, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(8, OUTPUT);
}

void loop() {
  String heartMonitor = codeWrite(4, HIGH, LOW, HIGH);
  String lilyPad = codeWrite(6, HIGH, LOW, LOW);
  String thermistor = codeWrite(8, HIGH, HIGH, LOW);
  Serial.println(thermistor);
  delay(1000);
}

String codeWrite(int pin, char output1, char output2, char output3)
{
  digitalWrite(pin, output1);
  int A = digitalRead(pin);
  delay(1);
  digitalWrite(pin, output2);
  int B = digitalRead(pin);
  delay(1);
  digitalWrite(pin, output3);
  int C = digitalRead(pin);
  delay(11);
  String code = String(A) + String(B) + String(C);
}

The issue is the code can not be outside of a function.


Transmit image file thougth the TX TR serial line I have a digital camera with a USB port for image dowload from the camera SD card.

I will like to be able to capture this image files store in the camera SD card using the Arduino  TX TR lines (serial) then transmit this image file to the computer from the USB connection from Arduino to Computer.

The reason need this scenario responds to that the camera dissables the shutter when sensing a USB cable conneted to computer. I do not knwo why this happens but I suspect is an underdeveloped feature of the camera.

Basically, I will like to use Arduino as a USB hub for external devices but at the same time to power down the line when no longer need the device using the Arduino TX and TX line . This will give tha camera a sense that the camera is been unplugged.

simulate this circuit – Schematic created using CircuitLab

You cannot. The TX and RX lines are UART. UART is not USB. USB is a very complicated protocol, and you need a proper understanding of how it works. It's not a simple serial protocol like UART.

Add to that the fact that the Arduino can in no way handle the amount of data involved in video, and you're already on a non-starter.


How can I programming detect that a Bulb/LED is ON/OFF or a circuit is working as expected using Arduino? I've created a circuit to turn on bulb using GSM module and Arduino. I want a mechanism(or programming) to know whether the bulb is on or off or fused. I've tried taking the input from the pins. But it only tells whether the pin is on or off but not the circuit as a whole.

This can be done using a few methods.  The simplest and least expensive option is to measure the current consumption of the device you want to verify correct operation of, and see if it's using enough, but not too much, current.

For instance, the following would work well in the arduino case of using an LED:

simulate this circuit – Schematic created using CircuitLab

Connect the Power to 5V or to the pin you're controlling the LED with. Connect the Sense to an analog input such as A0.

If the LED isn't installed, or is broken as an open circuit, the sense would register 5V.  If the LED is broken as a shorted element, the sense would register 0v. If the LED is operating correctly, you would sense the voltage drop of the LED (which varies according to the LED's design), but it would be well above 0V and well below 5V.

For bulbs and other loads, use a much smaller resister for R1 (so the resistor doesn't affect the load as much) and it would be considered a current shunt.  Knowing the resister value, and the voltage at the Sense location will give you a current value using Current = Voltage / Resistance. Again, the load should be drawing current within an acceptable range during proper operation.  If it's not drawing enough current, or too much current, it may not be operating correctly.

This won't tell you if the LED is on, however it's a very reliable method to discover if it's working correctly, and you'll probably never run into a situation where the correct LED is installed and in the right current range, but not emitting light.


Attempting to monitor serial output for a string to trigger function, apparently matching string is output but the function doesn't trigger I'm working on my second Arduino project, and am somewhat stuck.

I'm running a PIR module from my Arduino Uno with the following sketch:

/*
 *  PIR Sensor test
 */

 int pirPin = 6;

 int minSecsBetweenEmails = 60; // 60 seconds

 long lastSend = -minSecsBetweenEmails * 1000l;

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

  Serial.begin(9600);
 }

 void loop() {
  long now = millis();
  if (digitalRead(pirPin) == HIGH)
    {
       if (now > (lastSend + minSecsBetweenEmails * 1000l))
        {
            Serial.println("MOVEMENT");
            lastSend = now;
        }
      else
        {
          Serial.println("Too soon");
        }
    }
        delay(500);
 }

I'm monitoring the COM3 port using the following in JupyterLab with PySerial.

import time
import serial
import smtplib

to = 'myemail@myemail.com'
GMAIL_USER = 'myemail@myemail.com'
GMAIL_PASS = '**********'

SUBJECT = 'MOTION pir'
TEXT = 'PIR sensor detected motion'

ser = serial.Serial('COM3', 9600)

def send_email():
    print("Sending Email")
    smtpserver = smtplib.smtp("smtp.gmail.com",587)
    smtpserver.ehlo()
    smtpserver.starttls()
    smtpserver.ehlo
    smtpserver.login(GMAIL_USER, GMAIL_PASS)
    header = str('To:' + TO + '\n' + 'From: ' + GMAIL_USER)
    header = header + '\n' + 'Subject:' + SUBJECT + '\n'
    print (header)
    msg - header + '\n' + TEXT + ' \n\n'
    smtpserver.sendmail(GMAIL_USER, TO, msg)
    smtpserver.close()

while True:
        message = ser.readline()
        print(message.decode('utf-8'))
        if message[0] == 'MOVEMENT' :
            send_email()
            time.sleep(0.5)

I believe my problem is with the ser.readline() function. I've been reading the docs, they seem to say I need to provide some kind of endpoint or timeout for the function to provide for EOF, but my goal was to have the

if message [0] == 'MOVEMENT' :

continuously evaluate the output lines from COM3...

Any input at all would be very much appreciated.

EDIT: Thanks to all three of you for your help! By changing the Python as shown below I was able to fulfill the if message[0] == 'MOVEMENT' :statement

Python should have been:

import time
import serial
import smtplib

to = 'myemail@myemail.com'
GMAIL_USER = 'myemail@myemail.com'
GMAIL_PASS = '**********'

SUBJECT = 'MOTION pir'
TEXT = 'PIR sensor detected motion'

ser = serial.Serial('COM3', 9600)

def send_email():
    print("Sending Email")
    smtpserver = smtplib.smtp("smtp.gmail.com",587)
    smtpserver.ehlo()
    smtpserver.starttls()
    smtpserver.ehlo
    smtpserver.login(GMAIL_USER, GMAIL_PASS)
    header = str('To:' + TO + '\n' + 'From: ' + GMAIL_USER)
    header = header + '\n' + 'Subject:' + SUBJECT + '\n'
    print (header)
    msg - header + '\n' + TEXT + ' \n\n'
    smtpserver.sendmail(GMAIL_USER, TO, msg)
    smtpserver.close()

while True:
        message = ser.readline()
        print(message)
        if message == b'MOVEMENT\r\n' :
            send_email()
            time.sleep(0.5)

You're confusing readlines() with readline().  The former returns an array of lines, the latter a single line.  You need to drop the [0] since you're not working with an array of lines, and you need to include the line endings that the Arduino sends:

while True:
    message = ser.readline()
    print(message.decode('utf-8'))
    if message == 'MOVEMENT\r\n' :
        send_email()
        time.sleep(0.5)


How to get ESP8266 firmware version? I am going to update the firmware of an ESP8266 module, but first I would like to know the current version or name.

How can I get it? Maybe with an AT command?

This is my ESP8266 module:

ESP8266 and the AT firmware are products of Espressif. They have everything documented on the web site.

The AT command for version is AT+GMR.


How to flash an ATmega directly without a dedicated flashing device? An ATmega microcontroller can be flashed by a C compiler and a USB dedicated device (ISP).

I tried to flash the program into the microcontroller by saving the machine code to a MicroSD card that I then attached to the microcontroller. I figure we can use the USB SPI reader to test the program without dedicated device like USBtiny.

But I suspect that the compiler is just producing the hex file and then the USB will translate it to machine code.

Was I thinking wrong?

If the compiler loads the machine code through the USB programmer to microcontroller so don't we just need a MicroSD USB to program it?

Your initial assumption "An ATmega microcontroller can be flashed by a C compiler and a USB dedicated device (ISP)." is wrong.

The C compiler converts the source code into assembly language. It is then passed to an assembler which converts it to object code. The linker then creates an ELF file from it all. That is then converted into a HEX file using objdump.

That HEX file is then loaded by another program, avrdude, which knows how to control the USB-connected programming device. That device then issues special instructions to the chip through the ISP port to copy the data loaded from the HEX file into the memory of the chip in the right way.

It's quite a complex procedure and you require some active component in the mix to do the job. Just connecting an SD card and hoping it will work is, I am sorry to say, a laughable concept. You require something that a) understands how to read data from an SD card and can interpret it, and b) knows how to program an ATMega through ISP.

It is possible to create something that does that, using another chip, such as another ATMega, and writing the software to do it. If you feel adventurous, of course. You would basically have created a stand-alone programmer, which has advantages when you want to do field upgrades, but is pointless when you are sat at your desk developing software.


Arduino Mega and gyroscope erroneous values I have Arduino mega2560 and MPU6050.

I connected to Vcc pin of the gyro to +5V on the mega, the SDA to SDA pin, SDL to SDL pin, AD0 and GND to 2 GND pins.

I used this code:

#include<Wire.h>

const int MPU=0x68; //I2C address of MPU
int GyX,GyY,GyZ;
float pitch=0;
float roll=0;
float yaw=0;

float v_pitch;
float v_roll;
float v_yaw;
float a_pitch;
float a_roll;
float a_yaw;

void setup(){
  Wire.begin();
  Wire.beginTransmission(MPU);
  Wire.write(0x6B); //power management register 1
  Wire.write(0);
  Wire.endTransmission(true);
  Serial.begin(9600);
}

void loop() {
  Wire.beginTransmission(MPU);
  Wire.write(0x43);
  Wire.endTransmission(false);
  Wire.requestFrom(MPU,6,true);
  GyX=Wire.read()<<8|Wire.read();
  GyY=Wire.read()<<8|Wire.read();
  GyZ=Wire.read()<<8|Wire.read();
  v_pitch=(GyX/131);
  if(v_pitch==-1) {
    v_pitch=0;
  }
  v_roll=(GyY/131);
  if(v_roll==1) {
    v_roll=0;
  }
  v_yaw=GyZ/131;
  a_pitch=(v_pitch*0.046);
  a_roll=(v_roll*0.046);
  a_yaw=(v_yaw*0.045);
  pitch= pitch + a_pitch; roll= roll + a_roll;
  yaw= yaw + a_yaw;
  Serial.print(" | pitch = ");
  Serial.print(pitch);
  Serial.print(" | roll = ");
  Serial.print(roll);
  Serial.print(" | yaw = ");
  Serial.println(yaw);
}

But the values I am reading are not angles at all, plus when I move the X axes for 45 degrees, the value is not like that at all.

I don't want to use the pre made library as I want to understand how to read from Gyroscope. Any ideas?

It is possible to use your sketch and get angle information. It is not very accurate and it drifts.

I started with your sketch, and improved it until I had the angle.
The Serial.println functions take time and they are printed too often. To measure the interval between the samples, I used millis.

This test is done with:

arduino M0 board (with 3.3v i2c bus)
gy-521 module with onboard voltage regulator, but no level shifter
vcc of the gy-521 module connected to 5v (because of the voltage regulator)

The arduino M0 is faster than the arduino mega or uno.

// test with arduino M0 board
#include <Wire.h>

#define SER SerialUSB    // 'Serial' for arduino Uno, 'SerialUSB' for Leonardo and Arduino M0

const int MPU = 0x68;   // I2C address of MPU

int16_t x_offset = 0;
int16_t y_offset = 0;
int16_t z_offset = 0;

float pitch = 0.0;
float roll  = 0.0;
float yaw   = 0.0;

unsigned long previousMillisSample;
unsigned long previousMillisOutput;
const unsigned long intervalOutput = 500;  // half a second update to serial monitor

void setup() {
  SER.begin(9600);
  while(!SER);         // wait for serial monitor to open for Leonardo and M0
  SER.println("Angle from gyro");

  Wire.begin();

  Wire.beginTransmission(MPU);
  Wire.write(0x6B); //power management register 1
  Wire.write(0);
  Wire.endTransmission();

  // get the values of the gyro and use them as offset
  GetXYZ(x_offset, y_offset, z_offset);
}

void loop() {

  int16_t GyX;
  int16_t GyY;
  int16_t GyZ;

  GetXYZ(GyX, GyY, GyZ);

  unsigned long currentMillisSample = millis();  // time in millis when this sample is taken

  // remove offset
  GyX -= x_offset;
  GyY -= y_offset;
  GyZ -= z_offset;

  float v_pitch = float(GyX) / 131.0;    // convert to float and calculate degrees
  float v_roll  = float(GyY) / 131.0;
  float v_yaw   = float(GyZ) / 131.0;

  // calculate time in milliseconds between previous and current sample
  unsigned long t = currentMillisSample - previousMillisSample;

  // time in seconds as a float
  float float_t = float(t) / 1000.0;

  // adjust the number of degrees during the time
  float a_pitch = v_pitch * float_t;
  float a_roll  = v_roll  * float_t;
  float a_yaw   = v_yaw   * float_t;

  // remember the time in millis when the sample was taken for the next time
  previousMillisSample = currentMillisSample;

  pitch += a_pitch;
  roll  += a_roll;
  yaw   += a_yaw;

  // Once in a while, print the output
  if(millis() - previousMillisOutput >= intervalOutput) {
    previousMillisOutput = millis();

    SER.print("pitch = ");
    SER.print(pitch);
    SER.print(" | roll = ");
    SER.print(roll);
    SER.print(" | yaw = ");
    SER.println(yaw);
  }
}

void GetXYZ( int16_t &x, int16_t &y, int16_t &z) {
  // Get the gyro values
  Wire.beginTransmission(MPU);
  Wire.write(0x43);     // first register of gyro values
  Wire.endTransmission(false);

  Wire.requestFrom(MPU,6);
  x = Wire.read() << 8 | Wire.read();
  y = Wire.read() << 8 | Wire.read();
  z = Wire.read() << 8 | Wire.read();
}

Can you try this sketch? It drifts between 10 and 60 degrees per 5 minutes. That is a lot. I think the sensor is better than that, so that means the sketch is far from perfect.


Automate capturing photograph on ESP32-CAM I want to capture photographs from the ESP32 camera, but not doing it manually. Specifically, when a signal is sent from a sensor, I want ESP32 to understand that, and start taking photographs automatically for some seconds. The main problem, is the automation. I have searched on the web a lot, but can't find any answers. I am not expecting answers with code -since this is difficult- rather than some sites that provide solution to my problem. Thank you.

Please have a look https://github.com/Yurik72/ESPHap/tree/master/examples/ESPHAPCamera
The project has different things, but definetelly doing what you asked, captures photo by external event, command...


Serving binary file with ESP8266WebServer I am currently using a Nodemcu ESP8266-12E with the Arduino IDE in order to control my boiler. Everything is working fine, however I haven't figured out yet how to serve binary files, eg. images. (I am hosting them on a server at the moment).

ESP8266WebServer server(80);

void setup()
{
  [...]
  server.on("/", handleResponse);
  server.onNotFound(handleResponse);
  server.begin();
}

void handleResponse() {
  if (server.uri() == "/style.css") {
    server.send(200, "text/css", "[css]");
    return;
  }
  if (server.uri() == "/favicon.ico") {
    server.send(404, "text/html", "Not set");
    return;
  }
  [...]
}

unsigned char favicon_ico[] = {
  0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x10, 0x10, 0x00, 0x00, 0x01, 0x00,
  0x18, 0x00, 0x68, 0x03, 0x00,......... 0x00
};
unsigned int favicon_ico_len = 894;

Converting the arary to a string and serving it with server.send does not work and  server.stream expects a file.

It looks like you can use the send_P function to send raw PROGMEM data:

void send_P(int code, PGM_P content_type, PGM_P content, size_t contentLength);

I.e., (from what I can gather):

PGM_P favicon = {
  0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x10, 0x10, 0x00, 0x00, 0x01, 0x00,
  0x18, 0x00, 0x68, 0x03, 0x00,......... 0x00
};

server.send_P(200, "image/x-icon", favicon, sizeof(favicon));

Incidentally, PGM_P is just a typedef for const char *.


Switching 4.2V circuit with 3.3V Arduino GPIO I am trying to learn about MOSFETs and see this p channel MOSFET and this tutorial.  I am trying to use a 3.3V arduino GPIO pin to control a load that is powered from a 4.2V battery in much the same configuration as the circuit drawn in that tutorial.  Most other tutorials I see say the Gate Voltage needs to be equal or greater than the Source Voltage, but the tutorial I cited describes that actually the Voltage between the Gate and Source just needs to be more negative than the Threshold Voltage.  The P channel mosfet I cited is Vthreshold -2V to -4.  So my question is whether this P channel MOSFET would allow me to use a 3.3V arduino GPIO to control whether that 4.2V source is closed or open to the drain/load.  Looking at how that tutorial does the math, it seems in my case the GPIO being off would mean Vgs is 0 - 4.2 = -4.2 and therefore the MOSFET is in the ON state.  If GPIO is on at 3.3V then Vgs is 3.3 - 4.2 = -0.9 and therefore the MOSFET is OFF.  However, the tutorial doesn't say what happens when Vgate < Vsource but by an amount less than the Vthreshold so I don't know if my math is right.
In sum my questions are:

Is my math and prediction of the MOSFET states correct when that 3.3V GPIO is on or off?
If not, is it because of some other quality in this MOSFET and a different P MOSFET would work?
I presume that if I keep out of the Vgs upper and lower bounds then I avoid issues where the MOSFET is in a partially on and partially off state, is that correct?
Is it just impossible to use P MOSFETS in this way?

Note:  My questions only pertain to P MOSFETs.  For my project (switching a 1-2A disco light toy), it has to be a high side switch and that's even besides the point because I am more importantly trying to understand how the P channel mosfets work.

The MOSFET you chose will probably fail. Using a 30V device on a 24V system is asking for problems. Go to a minimum of a 60V MOSFET and use a UIS, Avalanche rated one. R4 is very week for what you need to do, I would suggest something in the 10K range to swamp out any leakage in the Arduino. If the MOSFET is properly rated the flyback diode is not needed but make a space for it incase you have to sub a MOSFET. Putting C2 in parallel with C1 will help. I do this a lot with electrolytics. I double up each one the needed size when one fails you don't notice it. I would suggest a couple of 220nF caps across the motor but that is application dependent.


How can I build a simple "Smartwatch" with Arduino Pro Mini and Display? I want to know how I can build a simple "Smartwatch" with an Arduino Pro Mini and a Display with a size from maybe 1,5" what Display should I use for Touch and color?

I only want simple things like synchonising the time with my Smartphone trough a HC-06 Bluetooth Module.

If your goal is to make a watch you'll need a RTC (Real Time Clock) this can take the form of breakout board, or you can build the circuit yourself. The RTC is needed if you want the mini to display the time. The mini (in fact, most micros) have no internal clock (though they may have a crystal that can simulate time keeping, but this isn't as useful if you want the time)

It sounds like you want an OLED display. They come in watch-like sizes. There are a few small ones. None are touch displays. I have seen larger touch displays. Maybe combine an OLED with a clear capacitive surface?


Outputting 400 mV using Arduino Nano PWM pin I am trying to output analog voltage (400 mV) using Arduino Nano PWM pins. Is it okay to directly connect (using jumper wires) the PWM pins to the Vin+ of the INA219 current sensor?

I badly need it for my graduation project. Thanks for the help.

PWM pins don't output analog voltages. They output pulses of 5V. You then need to average the output in order to get an actual analog voltage out of it. You should be able to use a capacitor and resistor to average out the voltage of the PWM pin, making a low-pass filter. You won't get exactly to 400mV. If I remember correctly the PWM pin has a value of 0 - 255, and 1/255 is 0.0196 V after a good low-pass filter, or 19.6 mV, so analogWrite(pin,20) should get close to the 400mV you want.

Another option would be to use a voltage divider to the output to get the output you want. That way you can use the full range of analogWrite() in producing the 400 mV and smaller voltages, thus gaining precision. Then again, if all you want is a fixed 0 or 400mV you could accomplish that with a digital output pin and a fixed voltage divider - no need for PWM.


Lost AT+ commands on ESP8266 after flashing with "blink" sketch I set my ESP8266 ESP-01 to flash mode and uploaded the example blink sketch on the arduino IDE esp example options. I know can no longer communicate with the ESP8266 using AT+ commands. I also cannot flash the device and can only receive the following message under baud 74880

"
 ets Jan  8 2013,rst cause:2, boot mode:(3,6)

load 0x4010f000, len 1264, room 16
tail 0
chksum 0x0f
csum 0x0f
~ld
"

Anyone know how to fix this? Thanks.

Thank you Juraj!

I had attempted to update the firmware multiple times and after 6hrs of trying was giving up. I really thought I had trashed my ESP-01. My post here was my last attempt to resolve the issue. I tend to have a problem of not asking for help until I'm frustrated. I saw your comment, and even though I had already attempted to reflash with new firmware I realized that you knew something I did not, and hopefully I could still salvage the ESP-01. So I downloaded documents about the esp8266 and decided to give it another try. What I found is my ignorance had let me believe that the esp-01 was broken when it was functioning as it should. Anytime you upload new firmware it will replace the old (including the at commands, but that's what it suppose to do). I then found this page that brought to my attention the mistake I was making. I was flashing the files to the wrong address, and there are multiple locations where the "blank" file needs to be flashed to.     So all is back to normal. At commands have returned. Now I have to remove them again to upload my program :).

https://www.allaboutcircuits.com/projects/flashing-the-ESP-01-firmware-to-SDK-v2.0.0-is-easier-now

I almost forgot to mention, I also had to hard wire my GPIO0 pin to ground before flashing. I was originally pulling GPIO0 to ground with a button. However, even though the serial console showed that I had booted in flash mode the flash tool failed. Only after hardwiring the GPIO0 to ground would the flash tool work.


Send Strings via SPI both ways using two Arduino UNOs(Master to Slave & Slave to Master) I need to create a two way String exchanger via SPI with two Arduino UNOs. Strings and their lengths are independent variables of the main loop and they can change with every iteration. I need both of the Arduinos to communicate with each other regardless of what the strings contain. I want to see basically the same screen with the serial monitor.

It is kind of working. I am not sure how to explain it, I'll just show it below.

Basically the main idea for both of the Arduino's is like this:

Master: hey
Slave: hi

Instead I get this on the master:

Slave:
Slave:
Master: hey
Slave: y
Slave:
Slave:
.
.
.
Slave: i
Slave:
Slave:
.
.

And the slave displays only itself:

Slave: hi

I have created for loops to transfer every char of the string seperatly and respectively but this is still the case. I couldn't find any sample code online for independent string transfering via SPI. I know I probably have many mistakes but how can I fix them to work just as I intend to?

Connections:

Arduino1.pin13 --- Arduino2.pin13

Arduino1.pin12 --- Arduino2.pin12

Arduino1.pin11 --- Arduino2.pin11

Arduino1.pin10 --- Arduino2.pin10

Master Code

//MASTER

#include<SPI.h>

String textSend="", textReceive="";

void setup(){

  Serial.begin(115200);

  SPI.begin();
  SPI.setClockDivider(SPI_CLOCK_DIV8);    //Sets clock for SPI communication at 8 (16/8=2Mhz)
  digitalWrite(SS,LOW);
}

void loop(){

  textSend=""; textReceive="";
  textSend = Serial.readString();
  if(textSend != ""){
    for(int i = 0; i < textSend.length(); i++){
      delayMicroseconds (20);
      SPI.transfer(textSend[i]);
    }

    Serial.print ("Master: ");
    Serial.println (textSend);
  }else{
    int i = 0;
    char c;
    do{
      delayMicroseconds (20);
      c = SPI.transfer(1);
      textReceive += c;
      i++;
    }while(textReceive[i] != 0);

    if(textReceive[i] == 0){
      Serial.print ("Slave: ");
      Serial.println (textReceive);
      textReceive = "";
    }
  }
}

Slave Code

//SLAVE

#include<SPI.h>

String textSend="";
String textReceive="";

void setup (void){
  Serial.begin(115200);
  pinMode(MISO, OUTPUT);
  SPCR |= _BV(SPE);
  SPCR |= _BV(SPIE);
  SPI.attachInterrupt();

}

ISR (SPI_STC_vect){ //Interrupt Service Routine

  byte c = SPDR;

  if(c != 1){ //Slave receives
    for(int i = 0; i < textReceive.length(); i++){
      textReceive += SPDR;
    }
    if(textReceive.length() > 0){
      Serial.print("Master: ");
      Serial.println(textReceive);
      textReceive = "";
    }
  }else{
    for(int i = 0; i < textSend.length(); i++){
      delayMicroseconds(20);
      SPDR = textSend[i];
    }
    if(textSend != ""){
      Serial.print("Slave: ");
      Serial.println(textSend);
      textSend = "";
    }
  }
}

void loop() {
  if(textSend == "")
    textSend = Serial.readString();

}

It's not trivial to have both arduinos communicating "with each other" as SPI is a master-slave bus. That means the slave cannot start a transmission, communication must always be initiated by the master instead. Another thing with SPI is that you can't read the slave without writing to it. SPI works like a shifting register: on every clock cycle both devices transmit the byte in their SPDR to each other. So, to read a long string from the slave the master has to transmit the exact same number of dummy-bytes and simultaniously read the incoming stream. This is great if only a specific number of bytes need to be transmitted (e.g. exchanging variables which always consist of the same number of bytes), but becomes complicate when the number of bytes varies. You will then need to implement some protocol that is able to read a variable amount of bytes from the slave (e.g. you will have to tell the master the number of bytes that have to be read).

I think serial communication like UART is perfect for your purpose as communication is real full-duplex, it's no master-slave-system and the common protocol uses a terminating character to end a data stream which makes it ideal to transmit strings. Also the arduino can run several serial interfaces (you might need another for debug output).