The problem of not saving the previous value when sending it from bluetooth Controlling Led's from Buttons and Bluetooth by same method

The problem now :

the LED light up when you send an A over Bluetooth and it will turn off after 2 sec automatically without you doing anything (this is the wrong now in video).

I Want the same char when send data the led turn on and when i want closed led send same char to turn off light .

The code: bottom this page

thank

this is the wrong now in video

 #define CLK 10
 #define CLKI 9
 #define LD 8
 #define SO 11
 #define SER 12

 byte ledstates;
 byte copy=0;
 unsigned long bt_leds_timestamp=0;
 byte bt_leds_activated=0;

 void setup(){
   Serial.begin(9600);
   pinMode(CLK,OUTPUT);
   pinMode(CLKI,OUTPUT);
   pinMode(LD,OUTPUT);
   pinMode(SO,INPUT);
   pinMode(SER,OUTPUT);
  }

 void loop(){
  if (Serial.available()>0){
  message();
 }
  shift_In();
  shift_out(ledstates);

  if(bt_leds_activated && millis()-bt_leds_timestamp > 2000){
  ledstates &= ~bt_leds_activated;
  shift_out(ledstates);
   bt_leds_activated = 0;
  }
 }

 void message(){
  if(Serial.available()){      // Send data only when you receive data:
  char data = Serial.read();        //Read   the incoming data & store into data
  Serial.print(data);          //Print Value inside data in Serial monitor

  switch (data){
  case 'A' :
    bt_leds_activated |= 1;
    break;
  case 'B' :
    bt_leds_activated |= 2;
    break;
  case 'C' :
    bt_leds_activated |= 4;
    break;
  case 'D' :
    bt_leds_activated |= 8;
    break;
  case 'E' :
    bt_leds_activated |= 16;
    break;
  case 'F' :
    bt_leds_activated |= 32 ;
    break;
  case 'G' :
    bt_leds_activated |= 64;
    break;
  case 'H' :
    bt_leds_activated |= 128;
    break;
  default   : return; }
  }
   ledstates |= bt_leds_activated;
   shift_out(ledstates);
   bt_leds_timestamp = millis();
  }

 void shift_out (byte copy){
  digitalWrite(LD, LOW);
  shiftOut(SER,CLK,MSBFIRST,copy);
  digitalWrite(LD, HIGH);
  delay(100);
 }

 void shift_In(){
  digitalWrite(CLKI,HIGH);
  digitalWrite(LD,HIGH);
  digitalWrite(LD,LOW);
  digitalWrite(LD,HIGH);
  digitalWrite(CLK,HIGH);
  digitalWrite(CLKI,LOW);
  byte buttonstates = shiftIn(SO,CLK,MSBFIRST); //read button states in a local variable
  digitalWrite(CLKI,HIGH);
  for(int i=0;i<8;i++){ // loop through all 8 bits of the buttonstates
    if(!(copy & (1<<i)) && (buttonstates & (1<<i))){ // check if old button state (in copy) is zero and new buttonstate is 1 (for the currently check bit)
        ledstates ^= 1<<i; // toggle the corresponding bit in the ledstates variable (will be shifted out later in the loop() function)
    }
  }
  copy = buttonstates;
  delay(10); // delay for debouncing
  }

C has an "Exclusive Or" operator which is ^.  You can use that instead of | so that it toggles the bit rather than always setting it:

case 'A' :
    bt_leds_activated ^= 1;
    break;

With ^ if you OR a 0 with a 1 you get a 1. If you OR a 0 with a 0 you get a 0. If you OR a 1 with a 1 you get a 0.

That means every time you send A bit one of bt_leds_activated will invert. If it's 0 it will become 1. If it's 1 it will be come 0.

Also you seem to have two sets of states - the button states, and the bluetooth states. Instead you only want one set of states, and both the buttons and the bluetooth toggle bits in that single state set.

Because of that if either of the methods of turning an LED on has turned the LED on then the other method will have no chance at all of turning the LED off.

So just drop bt_leds_activated completely and use ledstates:

case 'A':
    ledstates ^= 1;
    break;

Now both the button and the character through bluetooth will toggle the LED.


Problem in receiving message using GSM I have made modification of the code from GSM Modem with Arduino UNO

I have found a related question but it does not solve my problem. The message and command is printed in serial terminal of Arduino IDE but message is not received in the registered number. I am using SIM900A GSM module. Kindly direct me where I have gone wrong.

int pin = 4;
int val = 0;
void setup()
{
  pinMode(pin, INPUT);
  Serial.begin(9600);  //Baud rate of the GSM/GPRS Module
  Serial.print("\r");
  delay(1000);
  Serial.print("AT+CMGF=1\r");
  delay(1000);
  Serial.print("AT+CMGS=\"+919********5\"\r");
  delay(1000);

}
void loop()
{
  delay(1000);
  val = digitalRead(pin);
  delay(1000);
  if(val==1)
  {
    delay(1000);
    Serial.print("Found an object\r");
    delay(1000);
    Serial.write(0x1A);
    delay(1000);
  }
  val=0;
  delay(1000);

 }

If you want to use the Console monitor and the GSM at the same time, you need to use different pins to separate the communication streams.

Typically the console serial monitor is attached to Serial.*, while GSM modules are attached using SoftwareSerial to other pins.  See https://arduino.stackexchange.com/a/1195/6628 for an example.


Writing data to a specific address in EEPROM I'm trying to write two strings to an Arduino Uno's EEPROM. Here, the first code block works fine: it writes string(True/False) at 'address 0'. But the second block, which writes data at 'address 5', is not working as expected.Reading data at address 5 prints a blank line. What am I missing here? Is this the correct way to write two different strings to EEPROM?

First code block:

int state = LOW;
char first_eeprom_value;
if (state == LOW) {
  state = HIGH;
  char example_string[4] = "True";
  first_eeprom_value = EEPROM.read(0);
  Serial.println(first_eeprom_value);
  for (int i = 0 ; i < 5 ; i++) {
    EEPROM.update(i, example_string[i]);
  }
} else {
  state = LOW;
  char example_string[5] = "False";
  first_eeprom_value = EEPROM.read(0);
  Serial.println(first_eeprom_value);
  for (int i = 0 ; i < 5; i++) {
    EEPROM.update(i, example_string[i]);
  }
}
Time = millis();

Second code block:

char first_eeprom_value1;
if (state1 == LOW) {
  state1 = HIGH;
  char example_string1[4] = "True";
  first_eeprom_value1 = EEPROM.read(5);
  Serial.println(first_eeprom_value1);
  for (int i = 5 ; i < 11 ; i++) {
    EEPROM.update(i, example_string1[i]);
  }
} else {
  state1 = LOW;
  char example_string1[5] = "False";
  first_eeprom_value1 = EEPROM.read(5);
  Serial.println(first_eeprom_value1);
  for (int i = 5 ; i < 11 ; i++) {
    EEPROM.update(i, example_string1[i]);
  }
}

Time = millis();

//reading data at address 5
int addr = 5;
char value = EEPROM.read(addr);
Serial.println(value);// this prints blank line

You are cycling outside the string, thus creating undefined behavior.

Try replacing the second block with this:

char first_eeprom_value1;
if (state1 == LOW) {
  state1 = HIGH;
  char example_string1[4] = "True";
  first_eeprom_value1 = EEPROM.read(5);
  Serial.println(first_eeprom_value1);
  for (int i = 0; i < sizeof(example_string1); i++) {
    EEPROM.update(i + 5, example_string1[i]);
  }
} else {
  state1 = LOW;
  char example_string1[5] = "False";
  first_eeprom_value1 = EEPROM.read(5);
  Serial.println(first_eeprom_value1);
  for (int i = 0; i < sizeof(example_string1); i++) {
    EEPROM.update(i + 5, example_string1[i]);
  }
}

Please note that this is not optimal; I suggest you to use fixed-length strings, and fill the unused spaces with blanks or 0s, so you can read back all the bytes you wrote in a safe way


Problem sending data from arduino with ESP8266 to a local mysql database i'm currently trying to send a randomly generated number from Arduino via ESP8266 wifi module to a local mysql database estabilished with xampp, but having a problem with it. Here is my arduino and php receiving code. I should mention that i'm extremely unfamiliar with mysql, php, and the whole server & database things, so any help would be greatly appreciated.

Arduino Code:

#include <ESP8266WiFi.h>

const char* server = "192.168.1.106";
const char* ssid = "DARUSALAM C8";
const char* password = "asro4520";
const char* SensorID = "ESP001";

WiFiClient client;

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

  pinMode(BUILTIN_LED, OUTPUT);
  digitalWrite(BUILTIN_LED, HIGH);

  WiFi.begin(ssid, password);
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.print(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi Connected");
}

void loop() {
float n = random(300);

Serial.print("Random Number: ");
Serial.println(n);

  if (client.connect(server,80)) {
    Serial.print("Posting data...");
    digitalWrite(BUILTIN_LED, LOW);
    Serial.println("Random Number: " + String(n));
    client.println("GET /log.php?n=" + String(n));
    client.println("HOST: ");
    client.println(server);
    client.println("Connection: close");
    client.println();

    client.stop();
    Serial.println();

    digitalWrite(BUILTIN_LED, HIGH);
  }

  delay(5000);
}

PHP code:

<?php

$db_amb = mysqli_connect("127.0.0.1", "root", "", "wemos");
if (!$db_amb) die("Gagal terkoneksi ke DB Utama. Error : " . mysqli_connect_error());

$n = $_REQUEST['n'];
if (!empty($n) &amp;&amp;)
{
  $s = "insert into data_random set value1='$n'";
  $r = mysqli_query($db_amb, $s);
  echo "OK";
}
else echo "ERR";
?>;

The database is named 'wemos', and the table where i intend to store the data is named 'data_random' with 4 columns named value1-value4. My intentions is to store the random number to the 'value1' field.

EDIT the problem i encountered is whenever i checked http://localhost/log.php this appears:

Parse error: syntax error, unexpected ';' in C:\xampp\htdocs\log.php on line 7

i have tried modifying the syntax in numerous ways but the problem presist. I suspect my code may have some underlying fundamental problem that is not syntax related, but i can't tell due to my lack of experience. Again, any help/clue is greatly appreciated. Thank you very much

The HOST should not have a newline after it, so you should have

client.print("HOST: ");
client.println(server);

In addition your PHP looks dodgy to me.  I'm not very familiar with PHP at all, but I think the &amp;s here are left over from something you have removed, and causing syntax errors - just remove them

if (!empty($n) &amp;&amp;)

I believe your n parameter is going to be in _GET (not _REQUEST).  Also, you should check whether it's there, not just assume it is, so:

if isset ( $_GET["n"] )
{
    $n = $_GET["n"];
    // Do your database stuff here
}

(You should find the PHP log (where depends on what OS your server is running on) and I think it would point you straight to this problem.  No point trying to debug it blind.)


How to connect ESP8266-01 (AT-commands) to its web server using AJAX I am just new on using AJAX in web server, I got an error on declaring "server" I am confused about this because I just used only a AT commands to used the ESP8266-01 (wifi-module) I hope you can help me, I want to get the data (distance) to print in the web server(page) in real-time(no refresh). So I used the AJAX for it but this code is still error. Advance thanks on anyhelp :)

 #include "NewPing.h"
 #include <SoftwareSerial.h>
 #define DEBUG true

 SoftwareSerial esp8266(10,11);
 #define TRIGGER_PIN 4
 #define ECHO_PIN 3
 #define MAX_DISTANCE 400

 NewPing sonar(TRIGGER_PIN,ECHO_PIN,MAX_DISTANCE);

 void setup() {
 Serial.begin (9600);
 Serial.println("START");
 esp8266.begin(9600);

 server.on("/",WebsiteContent);
 server.on("/xml",XMLcontent);
 server.begin();

 pinMode(TRIGGER_PIN, OUTPUT);
 pinMode(ECHO_PIN, INPUT);

 sendData("AT+RST\r\n",2000,DEBUG);
 sendData("AT+CWMODE=2\r\n",1000,DEBUG);
 sendData("AT+CIFSR\r\n",1000,DEBUG);
 sendData("AT+CIPMUX=1\r\n",1000,DEBUG);
 sendData("AT+CIPSERVER=1,80\r\n",1000,DEBUG);

}

void javascriptContent(){
Javascript ="\n";

}
void WebsiteContent(){
javascriptContent();

 Website="\n";
 Website+="\n";
 Website+="";
 Website+="
"+data+"
";
 Website+=Javascript;
 server.send(200,"text/html",Website);
 }
 void XMLcontent(){

 XML ="<?xml version='1.0'?>";
 XML+="<data>";
 XML+=data;
 XML+="</data>";

 server.send(200,"text/xml",XML);

 }
 void loop()
 {

 delay(2000);
 digitalWrite(TRIGGER_PIN, LOW);
 delayMicroseconds(2);
 digitalWrite(TRIGGER_PIN, HIGH);
 delayMicroseconds(10);
 digitalWrite(TRIGGER_PIN, LOW);

 long duration,distance;
 duration= pulseIn(ECHO_PIN,HIGH);

 distance = duration/58.2;

 data=(String)distance;
 delay(500);

 server.handleClient();

 if(esp8266.available())
 {
 if(esp8266.find("+IPD,"))
 {
 delay(1000);
 int connectionId = esp8266.read()-48;

 String cipSend = "AT+CIPSEND=";
 cipSend += connectionId;
 cipSend += ",";
 cipSend +=webpage.length();
 cipSend +="\r\n";
 sendData(cipSend,1000,DEBUG);
 sendData(webpage,1000,DEBUG);
 String closeCommand = "AT+CIPCLOSE=";
 closeCommand+=connectionId;
 closeCommand+="\r\n";
 sendData(closeCommand,3000,DEBUG);

}
}
}
String sendData(String command, const int timeout, boolean debug)
{
String response = "";
esp8266.print(command);
long int time = millis();
while( (time+timeout) > millis())
{
  while(esp8266.available())
  {
    char c = esp8266.read();
    response+=c;
  }
}
if(debug)
{
  Serial.print(command);
  Serial.print("> ");
  Serial.print(response);
}
return response;
}

You're trying to mix code that is intended to run directly on an ESP8266 using ESP8266-specific libraries on an Arduino.  It can't ever work.

Likes like:

server.on("/",WebsiteContent);
server.on("/xml",XMLcontent);
server.begin();

are for use with the ESP8266's ESP8266WebServer library which doesn't run on an Arduino. To use these kind of constructs you have to program the ESP8266, not the Arduino, and then you don't have the AT commands available.

So, either:

Do it all with AT commands only, or
Ditch the Arduino and program the ESP8266 directly instead.


Sending values to an Arduino Yun across different networks I have quite a lot of experience with Arduino but have recently been faced with a challenge that has stumped me. The project is to create a robot that can be controlled from a separate network than it is on. I had the idea of using the Yun board to receive the values. Does anyone know a way I could have a computer send data to a Yun on a different network? (Maybe through a website?)

I have accomplished this, first by reading this article on controlling a Yun through a web-browser on the same network. From there it was a matter of allowing my Yun to be accessed externally (setting up port-forwarding on my router) and changing a few lines of code to reflect the new location reference.

All the necessary files and code are included under the heading "Project Files" in the above link and no modification is needed to get it working within the same network. That said, I had to convert the two .jpg files to .png (and change the filenames in index.html) - I don't know why they wouldn't show up in my browser.

In brief:

The Yun hosts a webpage (index.html) which contains some indicators and control inputs. These objects are linked to the 32u4 using Bridge and the REST API - nothing special. The bulk of the html code is for visual purposes, and the actual REST calls are nice and simple.

What is good is that the webpage can be accessed from anywhere with the right jiggery-pokery, and with a little more determination can be hosted from anywhere.

External Access

Once you have that working, you need to do the following to allow access externally. I tested this using my smartphone - disconnected from my home WiFi of course - to ensure the link was over the Internet, not intranet.

1) Set up port forwarding and a static IP for the Yun. This is the fundamental step if you simply want to control your Yun over the Internet. However, I can't actually tell you how to do this because I don't know what equipment you have! Information is all over Google for setting up both DHCP static IP and port forwarding.

2) Get a static IP from your ISP for your home/work, or set up a Dynamic DNS service (these people offer it free, but I've never actually needed to use an external service). Most commercial ISPs tend to dish out static IPs, but that's no guarantee that yours will.

3) Access your Yun with a browser via: http://YOUR.IP.ADD.RES:PORT/arduino/<SketchName>.

External Hosting

If you want to host the webpage on something other than the Yun, you can! You will of course need a server to host this, either your work's central server or an external hosting service. You'll need to change some more lines in the code:

1) In the Yun sketch change server.ListenOnLocalhost(); to server.noListenOnLocalhost(); - the subtle difference is the 'no', and is essential for external control. Sorry, that's incorrect without a little more explanation than is required at the moment to answer your original question.

2) In the .html file, you need to change each instance of:

server = "/arduino/<SOMETHING>";

to

server = "YOUR.IP.ADD.RES:PORT/arduino/<SOMETHING>";

If you have the REST password set to ON then you have to incorporate the username/password in there too:

server = "username:password@YOUR.IP.ADD.RES:PORT/arduino/<SOMETHING>";

There are three occurences in the original file, so be sure to catch them all.

3) When making changes to the .html file, make sure you re-upload it to the external host, not the Yun - that mistake took me hours to figure out.

A little more...

While searching for the URL of the article in the opening paragraph I found this atricle on a similar theme. It looks to have plenty of information although I haven't read it yet fully yet; I've been busy writing an answer on Stack Exchange. External Access should be no different, and if you want the 'External Hosting' version you just need to find any line that references the 'server' as "/arduino/..." and change it to "YOUR.IP.ADD.RES:PORT/arduino...".


How can i call lcd.begin() from several different code files in a proper way? I have a project split into several files:
//Loop.cpp
#include "LiquidCrystal.h"

void setup(){
    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
    lcd.begin(16, 2);
}

void loop() {
//Code
}

//Display.cpp
#include "LiquidCrystal.h"

namespace display {
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void displayData(const InputPacket &inputPacket, const DataPacket &dataPacket) {
    lcd.setCursor(0,1);
    lcd.print("Foo");    //This creates display error, unless i call lcd.begin(16, 2) in this function
}

} //namespace display

My initial problem is that - without calling lcd.begin() from within displayData() - the characters aren't displayed correctly. In other words, calling lcd.begin() in setup() doesn't help. (It appears to me that setup() has implicit static property, no?)
As an attempted solution, i could create an lcd object in Display.cpp, and call lcd.begin() from within displayData(). Even though characters are displayed properly, this gives me display flickering. (Presumably as a result of calling these functions repeatedly in the loop during runtime).
So, the only solution to this dilemma that i can come up with is to call lcd.begin() from a function written to run only once inside of displayData(). Or is it?
My question is, are there other more elegant solutions/alternatives?

The object called lcd that you create inside the setup function is a local variable. It only lives as long as that function is executing - so not very long. It doesn't exist outside that function.
The lcd object you have in namespace display on the other hand is a global variable. That one lives as long as your program, which means until you reset your Arduino here. (It is completely unrelated to the object inside setup.)
If you want all your LCD code to be grouped inside the display namespace, you could do this in Display.cpp:
namespace display {
  // This is a global variable, full name `display::lcd`
  LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

  void setup() {
    // this `lcd` refers to the global `display::lcd` defined above
    lcd.begin(16, 2);
  }

  // rest of the display functions
}

Create a Display.h file to provide prototypes for the display module:
#ifndef DISPLAY_H
#define DISPLAY_H

// Include the header that defines InputPacket and DataPacket here

namespace display
{
void setup();
void displayData(const InputPacket &inputPacket, const DataPacket &dataPacket);
}

#endif

Then your main file can call the display function. The main file doesn't even have to know that you're using an LCD if you do package all LCD code in the display file.
#include "Display.h" // no need to include LiquidCrystal.h if all
                     // LCD handling is done in Display.cpp

void setup(){
  // Initialize display
  display::setup();
}


How to connect an ESP8266 using an ESP-01 adapter to an Arduino Uno? I am pretty new to Arduino programming and wanted to learn how to connect an ESP8266 generic WiFi module to an Arduino Uno using the ESP-01 Adapter shown in the image below.
I tried doing it on my own while connecting the Vcc, GND, Tx and Rx pins of the adapter to the 5V, GND, Tx and Rx of the Arduino Uno respectively but was getting the following error while trying to upload the sketch:

warning espcomm_sync failed
error espcomm_open failed
error espcomm_upload_mem failed

To the best of my knowledge there is no tutorial on the internet that explains about the above mentioned adapter and its interfacing with the wifi module in detail. It would be a great help if someone could please guide me through the process so as to convert my Arduino into a server.

Recommended tutorial

you can't flash an esp-01 module with this adapter, unless you find a way to connect io 0 to ground in this setup

I have this type of adapter with esp8266 glued. I can't recommend this type of adapter boards. Easier is to use a development board like Wemos or NodeMCU with on-board USB adapter. And they are cheap.

The adapter has the esp-01 2x6 header J2 but the io 0 and io 2 pins were not connected on my version. I patched io 0 to JP2 header to be able to flash the module. On the picture you see a paperclip jumper connecting GPIO0 to ground.


Add id to raw data in an array I am working on an Arduino project, where I am transmitting GPS data between two Arduinos. This code can transmit the raw GPS data:

int a = Serial1.available();
if(a){
    uint8_t hej[a];
    for(int i=0; i<a; i++){
        hej[i] = Serial1.read();
    }

    rf95.send(hej, a);
}

I need to be able to identify the device that's transmitting the data. This can be in form of an integer value. I have tried to add a value to the array, but that messes up the data when I receive it.
Is there a simple way to add an ID to the data I am transmitting?

I would suggest:

Use a library (TinyGPS++ for example) to read the GPS data and extract just what you want.
Use a struct to craft a packet that you can send over bluetooth, or send the data as a textual representation, depending on your needs.

For a struct you can:

struct packet {
    uint8_t id;
    float latitude;
    float longitude;
};

struct packet myPacket;
myPacket.id = 32; // Unique ID
myPacket.latitude = gps.getLatitude(); // Whatever function call here
myPacket.longitude = gps.getLongitude(); // or whatever
rf95.send((uint8_t *)&myPacket, sizeof(struct packet));


How to determine the source of constants in libraries? Preamble:

I am trying to figure out how to program and use the timers in the Feather M0 using the Arduino IDE. I have seen a number of examples published, but I'm not one to just blindly copy some code and expect it to work. The issue that I'm having (and it seems to be ubiquitous in Arduino) is that there does not seem to be a concept of dependencies. In order to reference constants, they have to be defined somewhere.

Question:

How can I find the source of the definition of the constants that people keep referring to in their code? For example, in this code a Arduino Zero, M0 timer example, reference is made to TC_CTRLA_PRESCALER_DIV1 among other constants. Where is this constant defined?

Efforts:

I've searched generally and specifically for these constants. But, as you would imagine in C, it's difficult to find the actual source versus a simple reference to the constant.

I've also tried a search in the installed Arduino IDE with SAMD and Adafruit SAMD libraries installed. For example

~/Arduino$ grep -r --include=*.h --include=*.cpp "TC.*_PRESCALER_DIV"

Did not yield anything. I apologize if this is a naive question, but I haven't been able to find a simple, obvious answer. Actually, I haven't been able to find any answer.

The name TC_CTRLA_PRESCALER_DIV1 indicates this is a macro. A trick for quickly finding the exact location of a macro definition is:

File > Preferences > Compiler Warnings > All > OK
In your sketch, add a #define directive for the macro name that definitely changes the definition:

#define TC_CTRLA_PRESCALER_DIV1 foobar

Sketch > Verify/Compile
After the compilation finishes, examine the compiler output in the black console window at the bottom of the Arduino IDE window (you will need to scroll up to see it all) for a "redefined" warning. The warning will state the path of the original definition:

    C:\Users\per\AppData\Local\Temp\arduino_modified_sketch_804921\sketch_aug05a.ino:1:0: warning: "TC_CTRLA_PRESCALER_DIV1" redefined [enabled by default]

   #define TC_CTRLA_PRESCALER_DIV1 foobar

   ^

  In file included from C:\Users\per\AppData\Local\Arduino15\packages\arduino\tools\CMSIS-Atmel\1.1.0/CMSIS/Device/ATMEL/samd21/include/samd21g18a.h:268:0,

                   from C:\Users\per\AppData\Local\Arduino15\packages\arduino\tools\CMSIS-Atmel\1.1.0/CMSIS/Device/ATMEL/samd21/include/samd21.h:69,

                   from C:\Users\per\AppData\Local\Arduino15\packages\arduino\tools\CMSIS-Atmel\1.1.0/CMSIS/Device/ATMEL/samd.h:105,

                   from C:\Users\per\AppData\Local\Arduino15\packages\arduino\tools\CMSIS-Atmel\1.1.0/CMSIS/Device/ATMEL/sam.h:470,

                   from C:\Users\per\AppData\Local\Arduino15\packages\arduino\hardware\samd\1.6.19\cores\arduino/Arduino.h:48,

                   from C:\Users\per\AppData\Local\Temp\arduino_build_309126\sketch\sketch_aug05a.ino.cpp:1:

  C:\Users\per\AppData\Local\Arduino15\packages\arduino\tools\CMSIS-Atmel\1.1.0/CMSIS/Device/ATMEL/samd21/include/component/tc.h:113:0: note: this is the location of the previous definition

   #define TC_CTRLA_PRESCALER_DIV1     (TC_CTRLA_PRESCALER_DIV1_Val   << TC_CTRLA_PRESCALER_Pos)

   ^


Is the SIM800L 3G? Or is it able to connect to 3G? I am working on SIM800L. I am using a 3G SIM with a SIM800L. I am able to send messages and call using SIM800L, but when I am using the AT+HTTPINIT command it is not working. It is giving an error like operation unavailable. If wonder whether the SIM800L supports 3G/4G, or whether it only supports 2G.

Is the sim800L 3g? Or is the sim800L able to connect to 3g?

No, GSM and GPRS only. A SIM card is not specifically 3G. That depends on the network providers usage of SIM cards. Most providers will allow handover between 3G and GSM cells thus allowing GSM usage. The network provider may also allow roaming and handover to another networks for better coverage.

Check if your network provider has restrictions on the GSM/GPRS internet connection for the SIM.

Cheers!


GPS module Ublox Neo 6M issue I using the above mentioned GPS module with Arduino UNO. I find that I cannot receive the Latitude and Longitude values in the $GPRMC string in the NMEA data, as I used the module inside a concrete building. I got the values when I placed the module just outside the window. But I have noticed that the phones we use can get the location data just fine through their in-built GPS after waiting for just some time. How is this possible? Any way I can achieve this using the Ublox Neo 6M module?

Mobile phones use the mechanism of assisted GPS.

In contrast to your Arduino U-Blox module it uses the cell tower data your phone can provide to determine your location. This is especially helpful to get a quicker first fix and to get a fix even when you have poor satellite signal conditions.

That said, this will not be possible using only your GPS module connected to your Arduino.


I cannot compile the Arduino sketch when I remove the void loop function? #include <AFMotor.h>

AF_DCMotor motor(2,MOTOR12_64KHZ);

void movefor ();

void moveback();

    void setup()

    {

    Serial.begin(9600);

    Serial.println("Motor test!");` `motor.setSpeed(200);

    movefor ();
    moveback ();
    }

        void movefor( ){
        motor.run(FORWARD);
    delay(1000);
    motor.run(RELEASE);
     delay(100);
    }

    void moveback( ) {
      motor.run(BACKWARD);
    delay(1000);
    motor.run(RELEASE);
     delay(100);
    }

While trying to compile this the error message is error compiling for board Arduino Uno

I want the functions outside loop so removed it.

Even if I keep void loop and leave it blank then my motors will like run forward, backward and forward afterwards continuously .

You can't, and shouldn't, remove the loop function. Arduino sketches must have a setup function and a loop function. The setup function is called once and the loop function is called repeatedly.

Just make your loop function look like this:

void loop() {
    movefor ();
    moveback ();
}

Your motor will move forward, then move backwards, forever.

Note that you should read up on how to avoid using the delay function. You really need to use millis() to do your timing rather than delays. Do an internet search on "Arduino blink no delay." That's basic Arduino programming.


Unable to read data with 16 serial clock cycles I am trying to read data from an AD7314 Temperature Sensor that is connected to an Arduino Uno and output that value onto 6 LEDs also connected to the Arduino Uno board. From the image below, the sensor is showing only an output of 0011111111111111 during the streams of 16 clock cycles even after the chip enable goes from low to high before conversion to initiate a new one (it seems that the conversion is stuck). The datasheet says:

  A leading zero and 10 bits of data are transferred during a read operation. Read operations occur during streams of 16 clock pulses. Output data is updated on the rising edge of SCLK. The serial data is accessed in a number of bytes if 10 bits of data are being read. At the end of the read operation, the SDO line remains in the state of the last bit of data clocked out of the AD7314 until CE returns low

I am not sure where exactly I am going wrong during the read operation:

Note: for the Waveform image (Top to bottom):

waveform 1: Chip Enable
waveform 2: Serial Clock
waveform 3: MISO Line
waveform 4: MOSI Line

My code is below:

#include <SPI.h>

const int MOSI_PIN = 11;
const int MISO_PIN = 12;
const int SCK_PIN = 13;
const int Slave_PIN = A0;

// module data
uint16_t myValFromTempSensor = 0;

void setup () {
  SPI.begin ();
  SPI.beginTransaction(SPISettings(125000, MSBFIRST, SPI_MODE0));
  pinMode(5, OUTPUT); //LED 3
  pinMode(6, OUTPUT); //LED 4
  pinMode(7, OUTPUT); //LED 5
  pinMode(8, OUTPUT); //LED 6
  pinMode(9, OUTPUT); //LED 7
  pinMode(10, OUTPUT);//LED 8
  pinMode(MOSI_PIN, OUTPUT); // MOSI to SDI
  pinMode(MISO_PIN, INPUT); //MISO to SDO
  pinMode(SCK_PIN, OUTPUT); //CLOCK PIN to SCK
  pinMode(Slave_PIN,OUTPUT); //Slave pin

  digitalWrite(Slave_PIN, LOW);//Set slave low before communication
  for (int i = 5; i < 11; i++) {
    digitalWrite(i, LOW);
  }
  delay(100);
} // end of setup

void loop () {
  digitalWrite(Slave_PIN, HIGH);  //Set slave high to read data
  myValFromTempSensor = SPI.transfer(0x00); // Read Data from the device
  myValFromTempSensor |= (uint8_t)SPI.transfer(0x00) << 8;// Bitshift to read next 8 bits
  digitalWrite(Slave_PIN, LOW);
  if(( myValFromTempSensor>=0) && ( myValFromTempSensor<=196)) {
    //Range 0C to 60C is  0 to 196
    digitalWrite(5, bitRead(myValFromTempSensor,0));
    digitalWrite(6, bitRead(myValFromTempSensor,1));
    digitalWrite(7, bitRead(myValFromTempSensor,2));
    digitalWrite(8, bitRead( myValFromTempSensor,3));
    digitalWrite(9, bitRead( myValFromTempSensor,4));
    digitalWrite(10, bitRead( myValFromTempSensor,5));
  } else {
    digitalWrite(5, 0);
    digitalWrite(6, 0);
    digitalWrite(7, 0);
    digitalWrite(8, 0);
    digitalWrite(9, 0);
    digitalWrite(10, 0);
  }
}

This is not an answer to your question but I cannot add it as a remark since it involves code.

You can greatly reduce your code by using for loops, e.g.:

   pinMode(5, OUTPUT); //LED 3
   pinMode(6, OUTPUT); //LED 4
   pinMode(7, OUTPUT); //LED 5
   pinMode(8, OUTPUT); //LED 6
   pinMode(9, OUTPUT); //LED 7
   pinMode(10, OUTPUT);//LED 8

to

   int n;
   for (n = 5; n < 11; n++)
   {
      pinMode(n, OUTPUT);
   }

And

digitalWrite(5,bitRead( myValFromTempSensor,0));
digitalWrite(6,bitRead( myValFromTempSensor,1));
digitalWrite(7,bitRead( myValFromTempSensor,2));
digitalWrite(8,bitRead( myValFromTempSensor,3));
digitalWrite(9,bitRead( myValFromTempSensor,4));
digitalWrite(10,bitRead( myValFromTempSensor,5));

to

int n = 0;
for (n = 0; n < 6; n++)
{
    digitalWrite(n + 5,bitRead( myValFromTempSensor, n));
}

And

  digitalWrite(5,0);
  digitalWrite(6,0);
  digitalWrite(7,0);
  digitalWrite(8,0);
  digitalWrite(9,0);
  digitalWrite(10,0);

to

int n;
for (n = 5; n < 11; n++)
{
    digitalWrite(n, 0);
}

Instead of hardcoded values 5 and 11 you can use defines, e.g.

#define LED_MIN 5
#define LED_MAX 11

and change

for (n = 5; n < 11; n++)

to

for (n = LED_MIN; n < LED_MAX; n++)


Referencing local libraries from higher dir levels How can I include libraries not contained in any direct subdirectories of a sketch, using the Arduino IDE?

I want my project structure to look like this:

Project
└> MCUa
   └> MCUa.ino
└> MCUb
   └> MCUb.ino
└> Libraries
   └> TimerLib
      └> TimerLib.cpp
      └> TimerLib.h

So in my project two sketches MCUa and MCUb share a resource, namely the library TimerLib.

I've tried to include the libraries like this:

#include "../Libraries/TimerLib/TimerLib.h"

or this:

#include "./../Libraries/TimerLib/TimerLib.h"

But none of them will compile - this is the error message:

fatal error: ./../Libraries/TimerLib/TimerLib.h: No such file or directory
 #include "./../Libraries/TimerLib/TimerLib.h"
                                              ^
compilation terminated.
exit status 1
Error compiling.

If I put the library directly in of the directories and reference it like this:

#include "./Libraries/TimerLib/TimerLib.h"

Everything goes well.

Using an absolute path like in this answer is not a possibility in this case, as it should compile out of the box for others, without modifying any absolute paths.

The problem with a relative path for an include is that it has to be relative to one of the predefined list of existing include directories. This includes:

Compiler include locations
The Arduino core files
The locations of other included libraries
The build folder for the sketch

What it does not include is the location of the sketch, so you cannot specify a location relative to the sketch itself.

Further, even if you could, the compiler wouldn't know what library it was supposed to be referencing so, while the header would be found, any source files associated with it would be ignored and linking would fail miserably.

Instead you will have to place the library in a standard library location, such as the libraries folder in your sketch book.


Why is there a clock in my arduino? Of course I know it is usefull to control the time of a delay, but any other use?

With a 16Mhz clock, each line of my program will take 1/16000000 second, right?

even a very very big line will only take 1/16000000 of a second ?

With a 8MHz clock, each line will take the double of the time, right?
So the whole "main loop"  will take the double time too, right?

Why is there a clock in my arduino?

Because that is how computers and microcontrollers, etc, work.

  With a 16mhz clock, each line of my program will take 1/16000000 second, right?

No.

  even a very very big line will only take 1/16000000 of a second ?

No.

The clock defines at what speed the machine code instructions are fetched from memory and executed. Most instructions take 1 clock cycle, but some take more.

One line of C code may be compiled into any number of assembly instructions, which then get converted into machine code (raw numbers).  That could be anywhere from 1 assembly instruction to thousands of assembly instructions, depending on what the line does.

  With a 8mhz clock, each line will take the double of the time, right? So the whole "main loop" will take the double time too, right?

Every operation in the chip is governed by the clock. If the clock is half the speed the chip is running at half the speed, so every operation will take twice as long, yes.


How to vary the frequency of a PWM sinewave with arduino uno? I'm generating a sine wave using a table, a PWM pin and an RC filter on the output. I would like to be able to control the frequency of the sine wave, how can I do that easily?

By the way, which is the maximum frequency achievable and why? As far as my understanding goes, the limit is given by the time arduino needs in order to run the loop() function.

This is the code I am using on arduino UNO. Please point it out if this is a horrible way to generate a sine wave with arduino, and if it is, feel free to provide a better solution.

const int8_t SIN1024_DATA [] = {... data table values (1024 values) ...};
int i = 0;
void setup()
{
  pinMode(9, OUTPUT);
}

void loop()
{
  digitalWrite(9, SIN1024_DATA[i]);
  i++;
  if(i == 1024){i = 0;}
}

First thing, you must find a way to output the samples at a steady rate.
Your best bet is to use a timer. Ideally, you want to use the same timer
used for the PWM output, in order to have them synchronized. See for
example how it is done in the Mozzi sound synthesis
library.

Then you can lower the frequency by repeatedly outputting the same
value: if you output every value once, you get the “base” frequency
(sample frequency ÷ 1024). If you output each value n times you get
the base frequency divided by n. Conversely, you can get higher
frequencies by skipping samples. For example, if you output only every
other sample, you get twice the base frequency.

These two approaches can be conveniently combined in a very simple code:
you keep a phase variable and, on every sample, you increment it by an
amount proportional to the desired frequency. You then use the higher
bits of the phase as an index into your array. The lower bits then serve
only to increase the frequency resolution and allow frequencies lower
than the base one. Here is a simple implementation:

const uint8_t pin = ...;
uint8_t frequency;

// Call periodically.
static inline void output_a_sample()
{
    static uint16_t phase;
    analogWrite(pin, SIN1024_DATA[phase>>6]);
    phase += frequency;
}

This lets you set the frequency in units of the sampling frequency ÷
216, i.e. the base frequency ÷ 26.

Note that the phase here is 16-bits: 10 bits for the array index and 6
bits for the fractional part. Since all the bits are used, you do not
need to handle the rollover: a uint16_t automatically rolls over
modulo 216, which is just what you want here. You can use a
32-bit variable if you need more frequency resolution.


Arduino Nano IoT Power Consumption I am trying to reduce the power of my Arduino Nano IoT. I would like to run it using a battery over a longer time period. I thought this would be possible when putting it to sleep most of the time. However, at the moment I can only reduce the power consumption to 10mA by

disabling wifi using the WiFiNINA library
putting the arduino to sleep using the ArduinoLowPower library
removing both LEDs
powering it through a 4,5V battery

Is there anything else I can do to further reduce power consumption? If not, is there another, more suitable device I can use instead for this project? It has to support wifi and use very low power during sleep.

Two of those 10mA come from the ATECC608 crypto chip which idles at 2mA.  That leaves 8mA for you to track down.

The WiFi-NINA module has multiple "sleep" modes that range from 30mA down to 4.5µA. Since you can't be in the 30mA "modem sleep" mode (it's too high for your measurements) I suspect it enables "light sleep" at 800µA.

The switching regulator uses 200µA.  So those two together probably account for 1mA in total, leaving you 7mA more to find.

The accelerometer can be up to 1.25mA. I'll assume that since you don't mention it, you haven't set that to "power down" mode.  5.75mA left.

The main MCU is actually quite hungry for power, even when sleeping. Looking at the datasheet it can be between 1.3mA and 2.4mA for the different "idle" modes. Only "standby" mode (where clocks are switched off, etc) drops it below 1mA. With it running a simple program you are looking at 4-6mA.

So it could be that the MCU isn't actually sleeping properly, or that other modules that you think are in low power aren't.

I would suggest manually disabling chips completely (pull their respective RESET pins if available LOW if available) to see how that affects the current.


WizNet chip on Ethernet Shield oddly hot I'm making a thermometer and, so I can graph the data, I have an Uno with the WizNet shield sending the data to a LAN ip. The chip itself is oddly hot, its temperature measures at around 110-120ºF (43.33-48.89ºC). I want the program to be running almost 24/7. Is it okay for the chip to be this hot?

According to the WizNet forums this is normal for these shields. Their justification being that it is a PHY and controller on a single chip. (Note this post only specifically mentions the W5100, which is among the more commonly used chips on these kinds of shields, however, I suspect that this is typical for most of the WizNet line, e.g. W5200 etc.)


Detecting I2C transfer with LED I am going to do a project with a lot of Arduinos connected via I2C, where like of them can became master for a moment to announce an event. So I would like to see how much is the bus used. As there will be a central point, I thought about putting a LED there, from +5V to clock line, so it would shine when the transfer occurs and be black when the line is free. And so I would be able to guess the utilisation level of the bus. (The clock is effectively PWM going to zero often while in transfer, while being plain +5V when no transfer is active).

Of course direct connection is not the best idea, as it would disrupt the pull-ups and mess with the protocol (as it would drain a lot of power to clock each time it went down), there should be some separator/amplifier.

The question is - does anybody know a simple setting, where the LED would be driven by a small current to zero (that is inverting amplifier as simple as possible with high enough input impedance to not disturb I2C communication)?

Thanks for all hints :)

It can be done with two N-channel MOSFETs or one P-channel MOSFET (depending on what you have locally / can get / is in your bits box):

simulate this circuit – Schematic created using CircuitLab

In the left schematic the first MOSFET acts like a NOT gate, and the second is a simple low-side switch. The pair together make an active-low low-side switch.

The right hand schematic, which is somewhat simpler, uses a single P channel MOSFET as a high-side switch. This is normally driven with an N-channel MOSFET to invert the logic, since it is naturally active-low. You don't want that, so you can just connect direct to the gate.

Note that all MOSFETs are "logic level" with a threshold voltage below 3V (or -3V in the case of the P-channel).


How do I split a number into individual digits? How would I split part1 into 2-3 digits and put them into num1, num2, and num3?

int FMSTATION = 10250;

int update_display() {
  int fm_station = FMSTATION ;

  int part1;
  int part2;

  part1 = (FMSTATION / 100);
  part2 = (FMSTATION % 100);
  part2 = (part2/10);

  int num1 = ;
  int num2 = ;
  int num3 = ;
  int num4 = part2;

  matrix.writeDigitNum(0, num1, false);  //1st number on lcd
  matrix.writeDigitNum(1, num2, false);  //2nd number on lcd
  matrix.writeDigitNum(3, num3, true);   //3rd number on lcd and adds "."
  matrix.writeDigitNum(4, num4, false);  //4th number on lcd

  matrix.writeDisplay();
}

I have searched the web from top to bottom, but could not find the answer. In the end what I should get displayed on my LCD is 102.5.

% 10 returns the final digit of a number. Dividing by 10 shifts the number one digit to the right.

So if you have the number 10250 as an integer you can get at each number with:

10250 % 10 = 0
(10250 / 10) % 10 = 5
(10250 / 100) % 10 = 2
(10250 / 1000) % 10 = 0
(10250 / 10000) % 10 = 1

So your code could be written as:

num4 = (fm_station / 10) % 10;
num3 = (fm_station / 100) % 10;
num2 = (fm_station / 1000) % 10;
num1 = (fm_station / 10000) % 10;

No need to mess with "part" variables.


Connecting DAC output from Arduino Due to another arduino I have an Arduino Due and I want to connect the output from the DAC as an input to an Arduino Uno's analog input pin. From this link http://forum.arduino.cc/index.php?topic=164763.0, user DuaneB suggested that a resistor should be used in series with the DAC output to prevent an excessive flow of current that could damage the pin. But he was talking about this when the question was about powering a motor using the current generated from the DAC's voltage.

However, is this series resistor required when simply connecting the output of the pin to the input of another pin? I haven't seen any issue when connecting the output of my Raspberry Pi's GPIO to an arduino's input.

The inputs to Arduino pins are CMOS inputs, and present very high impedance.  (There is a tiny capacitor on every CMOS input, and the only current into the input is the very small amount needed to charge that capacitor.)

You don't need resistors when connecting inputs and outputs (digital or analog) between Arduinos. Should be the same with Raspberry Pi GPIO lines, or any other CMOS devices.


How would I use Arduino microcontroller separately? I'm learning Arduino. I use Arduino Uno board with ATMEGA328-PU. I tried basic codes like LED blink, control of DC motor etc. Arduino board is used only when we program microcontroller, right? I mean, when we finish programming it, we can use microcontroller separately? If it can be used separately, we must have some "external" circuit as replacement for Arduino board, which allow us to use microcontroller in specific application. What type of circuit is used? I'm new in this field so don't blame me because of amateur questions.

Assuming you are going to upload the program into the ATmega328 on the Arduino, then take the ATmega328 out of the socket, and use it in your circuit, then a simple answer is to search for "minimal Arduino circuit"

An example returned by that search is "From Arduino to a Microcontroller on a Breadboard".

It lists:

a 16 MHz crystal,
a 10k resistor, and
two 18 to 22 picofarad (ceramic) capacitors

That is enough to run the chip at the same speed as the Arduino, and the code used on the Arduino to initialise its clock will work unchanged.

This should run okay directly from a battery supply of about 4.5V or 4.8V, or a good 5V power supply.

A better circuit, which runs at the same 16MHz speed as the Arduino is 'Shrimp It'. That shows a similar minimal circuit and a better 'protected' circuit which has a more reliable approach for its power supply. This is all you need to run off a 4.5V (e.g. 3 1.5V) battery power supply.

However, if you don't care about running at 16MHz, you could ditch the crystal and capacitors, and use the internal 8MHz oscillator, that will need the code to be slightly different. For example, the 8MHz clock is 1/2 the speed of the Arduino's standard 16MHz, so code like delay() will take 2ms instead of 1ms.

Further, the RESET button can be set up so it doesn't need the 10k pullup.

So, with some software changes (search the web for details), an ATmega328 could be used with no external components.

Alternatively, you might want to use a better power supply, for example a voltage regulator with the circuit of the protected 'Shrimp It', and be able to load the program onto the ATmega while on its board.

There are products which bundle that 'standard' set of parts (voltage regulator, plugs and sockets and protected 'Shrimp It' running exactly like an Arduino at 16MHz) with a very compact PCB. They are able to plug directly into a breadboard, and so can be used with veroboard/stripboard (or a PCB) to make the rest of the circuit.

One is a kit called 'Boarduino'from adafruit. That web site gives some details to sow how to do this yourself. It is a convenient-to-use version of the 'Shrimp It', on a compact PCB.

An alternative kit is the "Really Bare Bones Board (RBBB) kit". However it is available as the PCB only, which is the "Really Bare Bones board (RBBB)", though the same supplier as the RRRB kit.

Neither Boarduino nor RRRB has on-board USB upload circuit. However, you can use your Arduino to do that, for example "Using an Arduino as an AVR ISP (In-System Programmer)". Or you could buy a USB to UART cable.


How to speed up Due ADC I'm doing a project where in I'm using Arduino Due to measure the time difference of arrival of signals to four piezoelectric sensors. The piezo sensors where glued on a board and we want to localize the source of taps on the boards based from the TDOA of the vibration to the piezos.

Originally, we are using interrupts to raise flags once we have detected the signals (basically, we've set a threshold on the piezo voltage to say that we've 'detected' a signal) but that seems susceptible to noises especially when the environment has loud noises (music, voices on microphones, etc.).

So what we think as a solution is to perform signal processing. However, to do this, we need to measure the voltage of the incoming signal using the ADC.

So far, my target is to make the performance of this approach comparable to that of the one where we are using interrupts. As of now, the new approach is super sensitive to the difference on the taps giving it a high POE.

As I understand it, the main difference between the two approach is that the interrupt approach has a microsecond difference between counts making the difference of the taps to about 10 to 30 microsecond. However, the Analog approach has a 20 microsecond difference between each sample for each channel, making the count difference 20 second also. Even a count difference would make it 20 us.

Is there anyway to make this time faster? I know the ADC needs time to convert and push the data to the appropriate registers but I'm just trying to find ways to make this faster. I've read on the datasheet of the Due MCU that it has 14 ADC channels plus a temp sensor at the 15th. Maybe a way of doing this could be to reduce the number of channels? I don't know how.

Are there any way to make the ADC conversion of the Arduino Due faster?

Yes, there is a possibility to configure ADC to run faster, as it can handle 1Msps. For four ADC channels it means 250ksps each (with 1us time difference between samples). It's not possible with Arduino wrappers as they are way too slow and also waits for conversion end. You have to configure it directly in MCUs registers, so start with SAM3X8 datasheet.

In short: free running mode, sequenced readings like: 0 1 2 3, with interrupt on 4th sample, interrupt handler and some processing.


Controlling ceiling fan speed using Arduino Reference: https://arduino.stackexchange.com/a/12000/37585

Based on this post, if I want to control a 120V AC ceiling fan with an Arduino, there's a complicated bit of electronics that needs to be put in place.

There are only 3 wires that go to the ceiling fan itself, load, neutral, and ground. Hooking up a relay in the middle of the connection allows me to turn on and off the fan; cutting the power. This does not allow me to change the fan's speed.

There's a pull-switch inside any 3-speed ceiling fan that lets you alter the speed. Whatever this is doing, it should be able to be replicated. The question is, does it require a 4-channel relay and some extra electronics or does it require converting the 3.3V GPIO to 120V and enabling AC-style PWM? Or is it something completely different?

Or is it something completely different?

fairly easy to do.

approach 1 is phase based, like a typical dimmer. your arduino needs to detect zero crossing and control a triac. fairly common.

approach 2 is simpler but less common: put a mosfet inside a bridge so it can control an ac load. apply pwm to the mosfet and you are done.


Failing to read from DHT22 when multiple components on breadboard I've been trying to use DHT22 along with many other sensor components connected to breadboard. It seems to fail reading from the DHT22 when multiple components are connected and reads only when the wires are connected directly from arduino to DHT22. What could be the reason and how can i resolve it?

First off:
Welcome to Arduino Stack Exchange
Hopefully we can help you here, but you really need to include a lot more information in your question. You really haven't given us anything to work on here and should include as a minimum:

what other sensors you are using, including protocols and model numbers
a circuit diagram (or a very detailed verbal description of your connections)
your source code including the libraries you are using (no need to list the library code, just the #include line will do)

At this early stage I would guess you are using incompatible sensors. The DHT22 is a 1-wire device, but not all 1-wire devices are the same. It would be certainly possible to run multiple protocols on one pin, but you'd really need to know what you are doing, and it would be preferable that you didn't.
It could also be that you're mixing protocols and have completely incompatible sensors clashing. Especially if you've got something else on the line that is trying to be the master.
Include some more info, with photos and/or a circuit diagram and code and hopefully we can get you on your way.


How to wire and control a 16mm button with 2 legs using arduino? I can't find any tutorials online explaining how to wire and control a 16mm push button like the one in the picture:

Do  you have any suggestions as to how use it with an arduino or a raspberry pi?

A pushbutton is a pushbutton. It is a momentary switch. Since it has flexible wires, and needs a place to mount, you should probably wire it using a breadboard.
That pushbutton looks like a panel mount pushbutton. You might want to mount it in a pice of plastic or sheet metal. (Unscrew that nut up by the red part that you press. Measure the outside diameter of the threaded part. Drill a hole ≈1/64" (≈0.4MM) bigger than the switch diameter into the plastic/metal. Insert the pushbutton from underneath the panel. screw the nut back on to secure it. Tighten moderately tight with needle-nose pliers, being careful not to round off the corners of the nut.
To wire it:
Get a breadboard. Run wires from your Arduino to the breadboard.
Wire the pushbutton into the breadboard as well.
There are various libraries that offer switch debouncing, or you can write your own fairly easily.
I suggest using INPUT_PULLUP mode, and wiring your switch between an Arduino digital input and ground. When the switch is open, the input will read HIGH. When you press the the switch, the input will drop to LOW.
If you want to debounce the switch input yourself: When the switch changes state, note the value of millis(), and ignore any new changes for a brief period (try 20-100 mS).


Employing C++ code for Arduino I have Googled quite a lot regarding using a C++ program for uploading to Arduino and related, however I am confused now. Right, my problem is this:

I have written a C++ program which imports RGB data of a 24 bit bitmap (which was generated using Matlab) and now I would like to use this array (3 arrays - R,G,B) for an Arduino sketch to be used for a LED matrix project that I am working on. I am not exactly a programmer and hence had to resort to this path -- MATLAB to c++ and then Arduino, although this could be entirely done in C++ too (importing a bitmap and extracting pixel info). So, my C++ code spits out the 3 arrays and I am not sure how to get those into an Arduino sketch.

I read a lot about this and I understood this - As the Arduino "language" is C and C++ therefore it is possible to program an Arduino in C++/c. I need a maker file and a compiler. However my question is that isn't there a more non-programmer friendly way to get this done, some software or an IDE which supports Arduino programming in C++? I cannot understand much of this method, hence trying to bypass this.

If anybody's got any better method, I would be really glad if you could share it. I am also looking to use the Arduino package for MATLAB to send the array directly from there using serial communication. But I just wanted to make sure I at least tried this path.

Would really appreciate if somebody could offer some help. I am quite stuck here.

Can share any other info if required.

Thanks a lot!

EDIT 1:

To clarify as Nick Gammon pointed out in the comments below. In brief steps, this is what I have done till now:

Got a 24 bit bitmap (some random image)
Extracted the RGB data for each pixel using Matlab
Have 3 arrays of (for eg.) 122X300 dimensions whose every element has values between 0-255 (8 bit) and for R,G and B colors
Want to get these 3 arrays for use in Arduino sketch for further working
Stuck here - how to do that .....
So I did this - I imported that the RGB data into 3 separate text files and made a c++ program to read those arrays assuming that I should be able to then somehow use this program in Arduino sketch.
Now I am not sure what to do....my goal would be to have these 3 arrays (CRGB arrays, FastLED) in my arduino sketch which I can control and then upload to my Due.
On googling I found that to use c++ for arduino , you need the avr compiler and make file, which I want to avoid. Tried other IDEs too, Eclipse, PlatformIO too .. ummmm ... not that successful to be honest.
as per Paul's ans- Matlab to Arduino method I have to try.
Hope I have clarified my process till now :)

EDIT 2:

C++ code for reading the above array (thought I could use the output in Arduino)

#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string>
#include <conio.h>
#include <sstream>
#include <stdlib.h>

const int HEIGHT = 4;

const int WIDTH = 5;

using namespace std;

int main(){

  int array_req [HEIGHT][WIDTH];

string userinputprompt, filename;

userinputprompt = "COLORDATA FILENAME: ";

cout<<userinputprompt<<endl;

getline(cin,filename);

ifstream inputfile;

inputfile.open(filename.c_str());

 for (int i = 0; i < HEIGHT; ++i)
{
  std::string tmpString;
  std::getline(inputfile, tmpString);

 std::stringstream ss(tmpString);

 for(int j=0;j < WIDTH; ++j)
  {
    ss >> array_req[i][j];
  }
 }

    for(int p=0; p<HEIGHT; p++)
    {
      for(int q=0; q<WIDTH; q++)
    {
        cout<<array_req[p][q]<<" ";
    }
    cout<<"\n";
}

inputfile.close();
getchar();
return 0;

}

Here's a sample program you could use as reference, just replace the values in the array and adjust VALUES_NUMBER accordingly.

Disclaimer: I didn't try to compile/run it, but it should give you an idea of how to use the values you already have.

// These are Arduino Pins that support "analog" output.
const unsigned short ANALOG_RED_PIN = 3;
const unsigned short ANALOG_GREEN_PIN = 5;
const unsigned short ANALOG_BLUE_PIN = 6;

const unsigned int VALUES_NUMBER = 12;

const unsigned short REDS[VALUES_NUMBER] = {
  0x00, 0x01, 0x02, 0x03, 0x04, 0x05,
  0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B
};

const unsigned short GREENS[VALUES_NUMBER] = {
  0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B,
  0x00, 0x01, 0x02, 0x03, 0x04, 0x05
};

const unsigned short BLUES[VALUES_NUMBER] = {
  0x09, 0x0A, 0x0B, 0x03, 0x04, 0x05,
  0x00, 0x01, 0x02, 0x06, 0x07, 0x08
};

void setup() {
  pinMode(analogRed, OUTPUT);
  pinMode(analogGreen, OUTPUT);
  pinMode(analogBlue, OUTPUT);
}

void loop() {
  unsigned int counter;
  for (counter = 0; counter < VALUES_NUMBER; counter++) {
    analogWrite(ANALOG_RED_PIN, REDS[counter]);
    analogWrite(ANALOG_GREEN_PIN, GREENS[counter]);
    analogWrite(ANALOG_BLUE_PIN, BLUES[counter]);
    delay(1000); //sleep 1 second
  }
}


More than 4 PWM output at 25khz? Is it possible using an arduino to control more than 4 PWM fan at 25khz ?

I have found this but 4 PWM limited with an UNO

https://arduino.stackovernet.com/fr/q/8407

An other arduino, like a 2560 could be used ?

Thanks
Best regards
Sébastien

Indeed you could use a Mega. See this answer: it explains how
you can use Timer 1 on an Uno to provide two PWM channels at
25 kHz. This is the only 16-bit timer on that board. The Mega, on
the other hand, has four 16-bit timers: Timers 1, 3, 4 and 5. These
timers are almost identical to the Uno's Timer 1, except that they
provide 3 PWM channels each. So you have potentially up to
12 PWM channels that you can run at 25 kHz.

Now, look at this pinout diagram. Every pin labeled OCnx,
where n is either 1, 3, 4 or 5, and x is a letter, is a 16-bit PWM
output. Just take the code from the answer I linked to and adapt it to
the Mega. You configure all those timers in the same way, and you set
the duty cycle for pin OC3B by writing to the register OCR3B (and so
on...).


Why is my transistor getting very hot when controlling a 12V peristalic pump? I have followed this tutorial:

http://www.instructables.com/id/Automatically-water-your-small-indoor-plant-using-/?ALLSTEPS

Every time i try to run my circuit, My transistor gets very hot and breaks.

I have exactly the same parts as the tutorial. I have also tested the circuit with 3.3V Power supply and a diode instead of an engine, this works.

I am super thankfull for any answers.

Measure the Current through the motor, the PN2222 can pass a maximum of 600mA.
I would guess that just over half an amp would be enough for the motor but you can check what you motor is trying to pull by connecting it to 12 V direct and measure the supply current.
The only thing that will make the transistor hot is excess current


releasing memory in sub-function I'm doing a program who get a line from the SD and shows it, this function is called getData()

FULL CODE:

#include <SD.h>
#include <MemoryFree.h>

File myFile;
int stringIndex = 0;
int cursorPosition = 0;
char inputString [25];
char inputChar;
boolean endOfLine;
char fullPath[11];

void setup(){

  Serial.begin(9600);

  Serial.print("Initializing SD card.");
  pinMode(10, OUTPUT);
  digitalWrite(10, HIGH);

  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");

}

void loop(){

  Serial.println(getDataSD());

  Serial.print("freeMemory()=");
  Serial.println(freeMemory());
}

String getDataSD(){

  memset(inputString, 0, sizeof(inputString));

  getFileNameSD();

  myFile = SD.open(fullPath);

  if(myFile){
    myFile.seek(cursorPosition);

    endOfLine = false;

    while(myFile.available() && endOfLine == false){
      inputChar = myFile.read();

      if(inputChar == '*'){
        while(inputChar != '\n'){
          inputChar = myFile.read();
        }
      }else{
        cursorPosition = myFile.position()-1;

        if(inputChar == 10 || inputChar == ' ') inputChar = myFile.read();

        while(inputChar != '\n'){
          if(stringIndex < 25){
            inputString[stringIndex] = inputChar;
            stringIndex++;
            inputChar = myFile.read();
          }
        }
        inputString[stringIndex-1] = '\0';
        stringIndex    = 0;
        endOfLine      = true;
      }
    }
    myFile.close();
  }
  return inputString;
}

void getFileNameSD (){

  char folder[] = "/ACC";

  checkFolderSD(folder);

  myFile = SD.open(folder);
  myFile = myFile.openNextFile();

  if(!myFile) myFile.rewindDirectory();

  if(myFile){

    strcpy(fullPath,folder);
    strcat(fullPath,"/");
    strcat(fullPath,myFile.name());

    myFile.close();
  }
}

I don't have problem with this function(getDataSD). To get the name of the file, I've created another function who looks for a file in a specific folder, this function is called getFileNameSD()

I'm having problem with this last function, it's not releasing or overwriting some data, so every time it's called, it is stored new data in memory

I've included the memory Free library to see where is the problem. When I call the getDataSD and write the file manually I dont have problem.

myFile = SD.open("/ACC/11001");

Serial monitor

freeMemory()=6592
/-27/-26/-56/
freeMemory()=6592
/-27/-26/-56/
freeMemory()=6592
/-27/-26/-56/
freeMemory()=6592
/-27/-26/-56/
freeMemory()=6592
/-27/-26/-56/
freeMemory()=6592
/-27/-26/-56/

the memory always is the same.

but not when I call the getFileNameSD()

myFile = SD.open(getFileNameSD());

Serial monitor

freeMemory()=6571
/-27/-26/-56/
freeMemory()=6540
/-27/-26/-56/
freeMemory()=6509
/-27/-26/-56/
freeMemory()=6478
/-27/-26/-56/
freeMemory()=6447
/-27/-26/-56/

I know I'm doing something wrong with getFileName() but I don't know what is, can anybody help/explain me?

Ok,

I don't know, why your memory is leaking, but anyway, your program won't work safely.
You defined an array (fullPath) inside the local scope of your function. You return it, which means, you return a pointer to this array. But at the same time, this array gets invalid, because you leave the local scope of your function.

Better define that string outside the function and give it as a parameter to the function. Then you aren't in danger of accessing an invalid pointer. Furthermore your memory leak won't appear.


Analog input weirdness (barrel connector vs USB power) I noticed that my Arduino Mega performs differently in how it presents values from say analog input A0, depending on whether it is being powered by USB or by a fresh 9V battery wired and connected through the barrel connector.

There must be some sort of difference to what happens when both USB and the barrel connector are employed vs. just USB being used for power.

To be specific, when running just on USB power, the analog inputs seem to flicker more allowing for oversampling and measurements beyond the 10 bit accuracy of the DAC. In fact with analogReference(DEFAULT) it is possible with 64x oversampling to see 100uV level changes when only USB power is employed. Note that these changes are not just noise, they actually correspond to 100uV level changes in the input connected to A0 with high correlation.

As soon as I connect the barrel connector, the picture changes significantly. Values coming out of the ADC seem to pretty much snap and there is far less flicker. The ADC becomes, well, discrete and you get your 1,024 levels and that's about it. There may be a tiny bit of flicker as you increase or decrease voltage and approach the next increment, but this is not significant enough to actually increase the ADC resolution reliably.

Even going so far as setting the analogReference to EXTERNAL while the barrel connector is employed and connecting the AREF pin to the 5v connector directly, which by the way reads at 5.004 V  (unlike the 4.992 V it reads when USB is powering the device) still reproduces the problem.

Summary: Effectively, when running on USB power only I can oversample the analog inputs and get significantly more than 10-bit resolution. While when running using the barrel connector, with the USB still attached, I can only get the 10-bit resolution natively provided by the ADC.

If anyone has any ideas on what is causing this difference in behavior, I am all ears. If I failed to explain anything or perhaps created some confusion, I would be more than happy to clarify.

Note: This is an authentic Arduino Mega board.

Looking at the schematic the barrel plug has a couple of linear voltage regulators (top left of schematic), while the USB input just has a couple of MOSFETs (bottom right of schematic) which are basically just there to switch off the USB power if there is something plugged into the barrel jack (and also maybe provide a little input protection). So the Arduino is relying on the USB power to be pre-regulated. For the most part this is correct, but USB voltage can vary widely depending on the cable length (voltage drop), the power source it is connected to (no two computers or wall warts are the same), and how many devices are the same hub (if connected to a computer or hub). I would not rely on the two power sources being matched at all.

The flicker you are talking about sounds like the power coming from USB could have significant ripple. I doubt that the USB power is allowing you to "oversample". The way ADCs in AVRs work is they have a reference voltage and when sampling, will give you a reading of where the voltage is between 0 and the voltage reference. With a 10-bit ADC there are ~1000 steps, so to measure 100uV changes, you would have to have a 100 mV reference voltage, which according to the datasheet (p.379), the minimum is 1.0 V. Basically, it is physically impossible for the Arduino Mega to measure those kinds of changes.

What is more likely to be happening is that you are probably getting some weird aliasing between the ripple frequency of your USB voltage and the sampling frequency of your code. The best way to debug this kind of thing would be to pull out an oscilloscope and check if and how much ripple is coming off the USB power.

If accuracy is important to your project, and being able to accept both power inputs is a requirement, you might look into maybe getting your own external voltage reference and piping it into VREF. Otherwise, I would stick to only using the barrel plug as it is regulated and will be consistent.


Arduino code of making a LED digit display not functioning properly I want to make an LED one digit display using 14 leds used in pairs so I have 7 pairs which show number. (Similar to the display in calculators). Now the problem is that my code won't function properly. The problem that is arising is that the leds won't go off, all of them would work at the same time, here's the code

int a = 2;
int b = 3;
int c = 4;
int d = 5;
int e = 6;
int f = 7;
int g = 8;

void setup()
{
   for(int i = 2; i++ ; i<9)
   {
      pinMode (i, OUTPUT);
   }
}
void _1()
{
   digitalWrite ( b, HIGH);
   digitalWrite ( f, HIGH);
   delay(1000);
}
void _2()
{
   digitalWrite ( a, HIGH);
   digitalWrite ( b, HIGH);
   digitalWrite ( d, HIGH);
   digitalWrite ( e, HIGH);
   digitalWrite ( g, HIGH);
   delay(1000);
}
void _3()
{
   digitalWrite ( a, HIGH);
   digitalWrite ( b, HIGH);
   digitalWrite ( d, HIGH);
   digitalWrite ( f, HIGH);
   digitalWrite ( g, HIGH);
   delay(1000);
}
void _4()
{
   digitalWrite ( c, HIGH);
   digitalWrite ( d, HIGH);
   digitalWrite ( f, HIGH);
   digitalWrite ( b, HIGH);
   delay(1000);
}
void _5()
{
   digitalWrite ( a, HIGH);
   digitalWrite ( c, HIGH);
   digitalWrite ( d, HIGH);
   digitalWrite ( f, HIGH);
   digitalWrite ( g, HIGH);
   delay(1000);
}
void _6()
{
   digitalWrite ( a, HIGH);
   digitalWrite ( c, HIGH);
   digitalWrite ( e, HIGH);
   digitalWrite ( f, HIGH);
   digitalWrite ( g, HIGH);
   digitalWrite ( d, HIGH);
   delay(1000);
}
void _7()
{
   digitalWrite ( a, HIGH);
   digitalWrite ( b, HIGH);
   digitalWrite ( f, HIGH);
   delay(1000);
}
void _8()
{
   digitalWrite ( a, HIGH);
   digitalWrite ( b, HIGH);
   digitalWrite ( c, HIGH);
   digitalWrite ( d, HIGH);
   digitalWrite ( e, HIGH);
   digitalWrite ( f, HIGH);
   digitalWrite ( g, HIGH);
   delay(1000);
}
void _9()
{
   digitalWrite ( a, HIGH);
   digitalWrite ( b, HIGH);
   digitalWrite ( c, HIGH);
   digitalWrite ( d, HIGH);
   digitalWrite ( f, HIGH);
   delay(1000);
}
void _0()
{
   digitalWrite ( a, HIGH);
   digitalWrite ( b, HIGH);
   digitalWrite ( c, HIGH);
   digitalWrite ( e, HIGH);
   digitalWrite ( f, HIGH);
   digitalWrite ( g, HIGH);
   delay(1000);
}
void wait()
{
   digitalWrite ( a, LOW);
   digitalWrite ( b, LOW);
   digitalWrite ( c, LOW);
   digitalWrite ( d, LOW);
   digitalWrite ( e, LOW);
   digitalWrite ( f, LOW);
   digitalWrite ( g, LOW);
   delay(100);
}
void loop()
{
   _0();
   wait();
   _1();
   wait();
   _2();
   wait();
   _3();
   wait();
   _4();
   wait();
   _5();
   wait();
   _6();
   wait();
   _7();
   wait();
   _8();
   wait();
   _9();
   wait();
}

The problem is that it stays at _0 and then never changes. Any suggestions?

The for loop in your setup() function isn't quite right. The condition (i<9) and the iterator (i++) need to be the other way round, like this:

for (int i = 2; i<9; i++)
{
  pinMode (i, OUTPUT);
}


Endurance of Arduino UNO during 24/7 operations and mild power fluctuations I am designing an automation system for my research project and planning on using Arduino Uno to do the same. The program is to execute simple instructions based on few input parameters and does not need large computational powers. It is estimated it would take 26 minutes to run the program (26-minute cycle*) and it is expected that it would take anywhere from 3 weeks to 2 months to complete the project (1160 - 3300 cycles before reboot)
My question is as follows:

Is the Arduino Uno capable of surviving the extended service expectancy and execute the program correctly?
What is the influence of small voltage fluctuations on the endurance of electronics on the board?
Is a heat sink needed for this application? How to determine the power draw to choose heat sink size?
Is there any fatigue rating for the cyclic running of the program?

I am planning to power the entire system via a regulated 12V 600-watt battery bank and this bank would be periodically recharged.
*By cycle duration I mean the real word time required for completion of one batch. It is estimated that it's required to complete 1160-3300 cycles/batches for the research

Is the Arduino Uno capable of surviving the extended service expectancy and execute the program correctly?

Yes, it is. Though your program and wiring needs to be stable and correct.

What is the influence of small voltage fluctuations on the endurance of electronics on the board?

Depends on what you call small. As long as you don't enter the brown-out region (where the voltage is so low, that the Arduino goes into reset for safety) or giving a too high voltage to it (See the specifications for that), you should be fine.

Is a heat sink needed for this application? How to determine the power draw to choose heat sink size?

The power draw of the Arduino depends on what you are doing with it. The best way would be to just measure the current of your application. Then you get the power by multiplying current and voltage. Normally you don't need a heatsink with an Arduino. The only part, that can get hot, is the linear voltage regulator. Depending on what you are interfacing with the Arduino, you might need to put a small heat sink on that (12V is a bit on the high side of input voltage for the regulator. It will dissipate the excess 7V as heat, so 7V multiplied by the used current). The microcontroller on the Arduino will not get hot (unless you are doing something terribly wrong).
And you should make sure, that the current for extra peripherals in your project doesn't flow through the Arduino, since that will place an extra burden on the voltage regulator. It should flow past it (means you connect them in parallel to the voltage source).

Is there any fatigue rating for the cyclic running of the program?

No, not really. I think the flash memory (where the program is stored) has a data retention failure rate of less then 1ppm (parts per million) over 20 years. So the program will not be lost, until you plan to run your application a hundret years. Also there is no read limit on the flash memory, only a write limit.


I can't upload codes to my ESP8266 ,this is the error I encounter when i try to upload my code
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>

#ifndef STASSID
#define STASSID "your-ssid"
#define STAPSK  "your-password"
#endif

const char* ssid     = STASSID;
const char* password = STAPSK;

const char* host = "192.168.1.1";
const uint16_t port = 3000;

ESP8266WiFiMulti WiFiMulti;

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

  // We start by connecting to a WiFi network
  WiFi.mode(WIFI_STA);
  WiFiMulti.addAP(ssid, password);

  Serial.println();
  Serial.println();
  Serial.print("Wait for WiFi... ");

  while (WiFiMulti.run() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }

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

  delay(500);
}

void loop() {
  Serial.print("connecting to ");
  Serial.print(host);
  Serial.print(':');
  Serial.println(port);

  // Use WiFiClient class to create TCP connections
  WiFiClient client;

  if (!client.connect(host, port)) {
    Serial.println("connection failed");
    Serial.println("wait 5 sec...");
    delay(5000);
    return;
  }

  // This will send the request to the server
  client.println("hello from ESP8266");

  //read back one line from server
  Serial.println("receiving from remote server");
  String line = client.readStringUntil('\r');
  Serial.println(line);

  Serial.println("closing connection");
  client.stop();

  Serial.println("wait 5 sec...");
  delay(5000);
}

Try updating the Serial Driver in your system or try using lesser baud rate, i.e. 9600 instead of 115200.


Initializing an array within a class I'm making a game of snake on the adafruit Neopixel shield and have run in to a problem. How do you fill out an array (in this case a 5*8 array) with values once the class has been called.
This is my code so far

H file

#include <Arduino.h>
#include <Adafruit_NeoMatrix.h>
#include <streaming.h>

class Snake : public Adafruit_NeoMatrix
{
    public:
    Snake();
    void drawSnake();

    private:
    int snakeBoard[5][8];
};

CPP file

#include "Snake.h"

Snake::Snake() : Adafruit_NeoMatrix(8, 5, D6,
  NEO_MATRIX_TOP        + NEO_MATRIX_LEFT +
  NEO_MATRIX_ROWS       + NEO_MATRIX_PROGRESSIVE,
  NEO_GRB               + NEO_KHZ800)
{
  begin(); // start the matrix
  show();

  int snakeBoard[5][8] = {{1,1,0,0,0,0,0,0},
                        {0,0,1,0,0,0,0,0},
                        {0,0,1,0,1,1,-1,0},
                        {0,0,1,1,1,0,0,0},
                        {0,0,0,0,0,0,0,0}};
}

void Snake::drawSnake()
{
  for(int y = 0; y < 5; y ++)
  {
    for(int x = 0; x < 8; x ++)
    {
      Serial << "X: " << x << " Y: " << y << " Value" << snakeBoard[x][y] << endl;
      delay(100);
    }
  }
  drawPixel(5,5,Color(0,0,255));
  show();
}

When I run the program random garbage is printed in the serial monitor.

As already mentioned by @chrisl, you are creating a new local variable which overshadows your class member.

An easy way to get what you want is to memcpy your initial values into the array:

Snake::Snake() : Adafruit_NeoMatrix(8, 5, D6,
  NEO_MATRIX_TOP        + NEO_MATRIX_LEFT +
  NEO_MATRIX_ROWS       + NEO_MATRIX_PROGRESSIVE,
  NEO_GRB               + NEO_KHZ800)
{
  begin(); // start the matrix
  show();

  int initialSnakeBoard[5][8] {{1,1,0,0,0,0,0,0},
                        {0,0,1,0,0,0,0,0},
                        {0,0,1,0,1,1,-1,0},
                        {0,0,1,1,1,0,0,0},
                        {0,0,0,0,0,0,0,0}};
  memcpy(snakeBoard, initialSnakeBoard, sizeof(initialSnakeBoard));
}

You can achieve the same thing by utilizing C++11 constructor lists to initialize your members (see here):

Snake::Snake() : Adafruit_NeoMatrix(8, 5, D6,
  NEO_MATRIX_TOP        + NEO_MATRIX_LEFT +
  NEO_MATRIX_ROWS       + NEO_MATRIX_PROGRESSIVE,
  NEO_GRB               + NEO_KHZ800),
  snakeBoard {{1,1,0,0,0,0,0,0},
                        {0,0,1,0,0,0,0,0},
                        {0,0,1,0,1,1,-1,0},
                        {0,0,1,1,1,0,0,0},
                        {0,0,0,0,0,0,0,0}}
{
  begin(); // start the matrix
  show();
}

You also have an error in your drawSnake routine: You confused the order of the indexes. With snakeBoard[5][8] you declare 2-dimensional integer array with 5 rows containing 8 elements each. Then, snakeBoard[0] will be a pointer to the first row (which has 8 elements). So the first index is y and must only range from 0 to 4 inclusive. The function must be:

void Snake::drawSnake() {
    for(int y = 0; y < 5; y ++)
    {
        for(int x = 0; x < 8; x ++)
        {
            Serial.println("X: " + String(x) + " Y: " + String(y) + " Value " + String(snakeBoard[y][x]));
            delay(100);
        }
    }
}

This then prints all the expected array elements to the the Serial port, as tested on my Arduino Nano.


Convert to and from Unix Timestamp What is the best way to convert between date, hours, min, seconds to Unix timestamp in milliseconds in Arduino? I need to have this conversion, since I'm using RTC (date, hours, min, secs etc) and communicating Unix timestamp over BLE

I found some snippet of codes online, but have not tested it extensively yet.

  byte second = epoch%60; epoch /= 60;
  byte minute = epoch%60; epoch /= 60;
  byte hour   = epoch%24; epoch /= 24;

  unsigned int years = epoch/(365*4+1)*4; epoch %= 365*4+1;
  unsigned int year;
  for (year=3; year>0; year--)
  {
      if (epoch >= days[year][0])
          break;
  }

  unsigned int month;
  for (month=11; month>0; month--)
  {
      if (epoch >= days[year][month])
          break;
  }

  year  = years+year;
  month = month+1;
  unsigned int day   = epoch - days[year][month]+1;

  unsigned int weekday  = (dayOfMonth += month < 3 ? year-- : year - 2, 23*month/9 + dayOfMonth + 4 + year/4- year/100 + year/400)%7;

And to convert to Unix timestamp:

unsigned long epoch = (((year/4*(365*4+1)+days[year%4][month]+dayOfMonth)*24+hour)*60+minute)*60+second;

Are there any library in Arduino that implement this? I would trade off reliability over size of the program.

I think that the two most used libraries are the Adafruit RTClib and the pjrc.com TimeLib.
They both have functions to convert the epoch, and they both are reliable. But both lack the timezone and the DaylightSavingTime.
I think you find the pjrc.com TimeLib just slightly more suitable to handle the epoch time (which is a 32-bit unsigned long defined as 'time_t').


how can I upload a hex file to an arduino uno? I have a Rostock Max 3d with an Arduino Uno as the controller. The OEM has a firmware version I would like to upload, but it is in the hex file format.

I have looked all over the Arduino IDE, but did not found a way to upload a hex file to the Arduino. I tried using AVRDUDE, but the Arduino only communicates with my PC when I set the "Programmer" to AVRISP. I have uploaded other codes for blink, and hello_world, but haven't been able to compile the firmware source. I was hoping I could just use the hexfile included in the firmware package.

My OS is Linux.

I use a standalone programmer that uploads a .hex file from an SD card via the ICSP interface.


Use potentiometer to control motor's speed Following the arduino starter kit, one of the projects uses a push button to on/off a motor.

In the end they suggest to try to use a potentiometer to control the speed of the motor.
I already did it, but I am not sure how I should use the capacitors(I placed one with the pot).

In one of the previous examples they used 2 100uF capacitors(one for the pot. and another for a servo motor) and I was wondering if this would be the same case.

This is my circuit:

The code:

const int POT_PIN = A0;
const int MOTOR_PIN = 9;
int motorSpeed = 0;
int potVal = 0;

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

void loop()
{
  potVal = analogRead(POT_PIN);

  motorSpeed = map(potVal, 0, 1023, 0, 255);

  analogWrite(MOTOR_PIN, motorSpeed);
}

Previous example with capacitors:

Code:

#include <Servo.h>

Servo myServo;

int const POT_PIN = A0;
int potVal;
int angle;

int alpha = 0.8;
int rawReading;

void setup()
{
  myServo.attach(9);

  Serial.begin(9600);
}

void loop()
{
  rawReading = analogRead(POT_PIN);
  potVal = alpha*potVal + (1-alpha)*rawReading;
  Serial.print("potVal: ");
  Serial.print(potVal);

  angle = map(potVal, 0, 1023, 0, 179);
  Serial.print(", angle: ");
  Serial.println(angle);

  myServo.write(angle);
  delay(15);
}

Ah, now I see. Your confusion in this case is perfectly understandable. They threw a couple of capacitors into the circuit without explaining why they were added in the first place. In order to understand why capacitors were added you need to go a little deeper into electronics theory, specifically capacitance and inductance, what they are and how they work.

Inductance is, to put it succinctly, resistance (not related to the resistance in resistors, measured in ohms) to change in current by sacrificing or absorbing voltage. If current is 0, then inductance will try to keep it at 0, if at 1A then it will try to keep it at 1A, and so on. Inductance is caused by the magnetic fields generated by electricity flowing through a conductor, and hence every conductor exhibits some measure of inductance. (Coils have much higher inductance though, since the magnetic fields of the loops reinforce each other. And a "core" material such as ferrite or iron intensifies the magnetic field.)

Now, this isn't a large problem if your conductors are short, but as they get longer their inductance can cause power issues. Sudden power demand increases are unable to be accommodated because the supply can't put the increased current through the inductance quickly enough. This is where capacitance comes in.

Capacitance is resistance to change in voltage by sacrificing or absorbing current. When something tries to reduce the voltage either through power consumption or because of high-speed switching, capacitance holds the voltage as close to constant as it can by pulling or dumping electricity out of or into the circuit. Capacitance is caused by charges between two conductors attracting each other through a non-conductive material.

So what happens is that a circuit needs bursts of power to work, and if the wires connecting the supply to the circuit have too much inductance then the circuit will be starved of power. We balance this by placing a capacitance close to the circuit so that it can supply power to the circuit for the short time while the supply is busy overcoming the inductance of the wires.

The servo, being a mechanical device, needs a decent amount of power. We put a bulk capacitor near it on the supply lines to help provide this power. The analog input connected to the potentiometer needs much, much less power, so the inductance there isn't a problem and we forgo the capacitor there.


What is FaryLink? [Access Point] When powering up my WeMos D1 ESP8266, I suddenly find this hotspot named "FaryLink". What is this? I programmed the ESP to work as a web server, thus connecting to an existing hotspot and not providing any beacons or acting as an access point.

Google could not provide any information to this behaviour.

What is the purpose of this AP and how can I use / disable it?

Did you use setmode() to put it in station mode?

wifi.setmode()

Configures the WiFi mode to use. NodeMCU can run in one of four WiFi modes:

Station mode, where the NodeMCU device joins an existing network.
Access point (AP) mode, where it creates its own network that others can join.
Station + AP mode, where it both creates its own network while at the same time being joined to another existing network.
WiFi off.

When using the combined Station + AP mode, the same channel will be used for both networks as the radio can only listen on a single channel.

NOTE: WiFi Mode configuration will be retained until changed even if device is turned off.

Syntax

wifi.setmode(mode)

Parameters

mode value should be one of

wifi.STATION for when the device is connected to a WiFi router. This is often done to give the device access to the Internet.
wifi.SOFTAP for when the device is acting only as an access point. This will allow you to see the device in the list of WiFi networks (unless you hide the SSID, of course). In this mode your computer can connect to the device, creating a local area network. Unless you change the value, the NodeMCU device will be given a local IP address of 192.168.4.1 and assign your computer the next available IP address, such as 192.168.4.2.
wifi.STATIONAP is the combination of wifi.STATION and wifi.SOFTAP. It allows you to create a local WiFi connection and connect to another WiFi router.
wifi.NULLMODE to switch off WiFi

Returns

current mode after setup


Arduino Uno R3 USB is not working I have a problem with my Arduino Uno board. It's not mounting in my Linux machine, but its power is on and the LED light is glowing. It was working before. After I tested buttons with an 12 V external supply, I am facing this scenario.

I tried lsusb and I checked /dev/ ports. Also, I couldn't find `ttyACM. I tried with another Arduino board and it's working. I think the board is gone, and I need help to fix this problem.

I thought it was a bootloader problem, and I got a new ATmega328P chip board. It is getting power on and the LED is blinking, but the port is not mounted. I tried with lsusb and also ls /dev/ttyACM* with no result.

You could try to flash the firmware of the USB controller.

General steps for Arduino R3 are:

Put the Arduino in DFU mode (the R3 does not require soldering for that)
Flash the firmware using:

dfu-programmer atmega16u2 erase
dfu-programmer atmega16u2 flash Arduino-usbserial-atmega16u2-Uno-Rev3.hex
dfu-programmer atmega16u2 reset

The package "dfu-programmer" is most likely available for your distribution.

If you have to build it from source, because your DFU programmer does not know the ATmega16U2 yet, you will need to install libusb-dev (on Debian-based systems).

Useful links for that:

Resetting your Uno R3's default firmware
Updating the Atmega8U2 and 16U2 on an Uno or Mega2560 using DFU

A useful search term for that is Arduino R3 DFU-programmer.


Arduino around the Xmega? I came across a dev board around the Atmel Xmega controller. This an AVR like used on Arduino, but with a lot of extras.

I was surprised to see that the board is hardly more expensive than an Arduino, despite:

  384kB of Flash (versus 32kB for Arduino)
  DMA
  Xmega can run at 32 MHz (16 MHz for Arduino)
  on-board OLED display
  on-board light and temperature sensors
  on-board microSD socket

For all these on-board features you'd need a shield or breakout board for Arduino. I seems to me that for a lower price than Arduino you could build a much more powerful system, which is Arduino-compatible.
How hard would it be to port Arduino to the Xmega?

see also http://www.element14.com/community/docs/DOC-71436

There's an attempt to get the Atmel XMEGA boards working in Arduino IDE.

https://github.com/akafugu/Xmegaduino

It's not fully featured yet but appears to have to features to allow you to start hacking with this board.


Arduino Mega resets when DFPlayer speaker plugged into amp! I have a MP3 DFPlayer Mini connected to a Mega2560. I'm using serial to control it. The Mega is powering/grounding the DFPlayer, and USB is powering the Mega. If I plug a small speaker directly to the DFPlayer speaker pins, I hear the audio as expected. Tracks play correctly, at the proper volume, etc.

I also have a 20w audio amplifier (MAX9744, and 20w speaker ofc), powered separately by a 12v DC wall plug. If I plug an iPod into that via the stereo jack, I hear nice loud audio, as expected. Everything is fine.

For months, I have had the DFPlayer speaker pins supplying audio into the headphone jack on the amplifier. It has been working perfectly. Until recently...

Now, for some reason, the Mega2560 instantly resets, and will continue to reset every couple of seconds while the speakers are plugged in to the amplifier. As soon as the line in stereo jack is removed from the amplifier, the Mega works again.

This has me completely stumped. This setup has previously been working perfectly, for several months. The amplifier is clearly affecting the Mega somehow (via the DFPlayer!), even when no audio is actively playing. But I'm stuffed if I can figure out where the problem is!

I appreciate any ideas and suggestions you may have.

For externally amplified speakers, you should be feeding the DAC and GND pins to the amp's inputs.  Those DAC pins provide a signal that varies by a small number of volts and is shifted so that they're always positive.  This is in the range expected by small headphones (ear buds) and line level inputs to audio components like an amplifier.

The speaker pins on the DF Player mini are pre-amplified (a little tiny bit) to directly drive a very small speaker (like 2 Watts at 8 Ohms).  They are a differential signal that includes both positive and negative voltages (relative to GND).  Note that the two speaker outputs (SPK+ and SPK-) are not left and right, but two sides of a differential signal.  Based on the schematic on page 11 of the datasheet (Chinese), it's a mono output made from mixing the outputs of the left and right DACs.

I could see how you might have gotten away with sending those to the amp, since the pre-amped speaker outputs are low power, and a good amp probably has input protection.

I don't know enough about electronics to know why it's failing now when it seemed to be working before.  It could be sensitive to the amplifier's gain or a ground loop between the power sources, but I'm just shooting in the dark.  Somehow, I suspect the DF Player Mini struggled to provide enough current to your amp, and since the DF Player Mini was powered from your Arduino, the Arduino essentially browned out, triggering a reset.


Powering 12V keypad through Arduino Uno Arduino Uno

I'm currently working on a project which will involve entering a sequence on a 12V keypad. The keypad and its documentation can be found here: https://www.jaycar.com.au/digital-keypad-with-rfid-access-control/p/LA5353

They keypad wants 9-18V AC/12~24V DC. I'll be using the keypad to output 26 bit Wiegand to the Arduino. I'm just wondering the best way to power this system. The schematics included with the keypad show that the keypad and the controller  (Arduino) should be sharing a power source. See image attached.

How can I power the 12-24V keypad through the arduino without frying it?

How can I power the 12-24V keypad through the arduino without frying it?

If you power the Arduino with slightly more than 12V (through the barrel jack) then you can get 12V (or slightly less than you power the Arduino with) from the VIN pin.

However the Arduino's on-board voltage regulator does tend to get a little hot when such a high voltage is used to power it. Better is just to power the keypad separately from the correct power source.

And don't forget to connect the grounds together.


How to write a script if water sensor comes into contact with water for more than 2 mins and LED lights up I am a newbie to arduino and programming. I would like to come out with a code for water sensor to detect the presence of water for more than 2mins before lighting up the LED lightbulb. Currently using Arduino, Grove baseshield with grove water sensor http://wiki.seeedstudio.com/Grove-Water_Sensor/.

I have the simple base code but not sure how do i go about adding in the function to detect water for a longer period of time before the light lights up:

#define watersensor 8               //Grove water sensor to Arduino Digital Pin 8
#define led 4                      //Grove LED to Digital Pin 4

int isWater;
bool wasWater = false;
//bool isWater, wasWater = false;    // true => currently we are not seeing water
uint32_t waterstart_ms = 0;        // time first saw water

void setup() {
  pinMode(watersensor, INPUT);
  pinMode(led, OUTPUT);
}

void loop()
{
   // Is there water?
 isWater = digitalRead(watersensor);     // read sensor
 Serial.println(isWater);

   if( isWater ){
      if( wasWater ) {
      waterstart_ms = millis();  // First water: note the time
      }
        if( millis() - waterstart_ms >= 1*5*1000 ){// Water continues for 5s (trial first); time to light LED?
            digitalWrite(led, HIGH);
        }//end if
            wasWater = true;
   } // end first if
   else {
      wasWater = false; // No water; LED off
      digitalWrite(led, LOW);
   }
}

Should the LED be latched (stay on forever, once it's on), or go out if the sensor later detects no water? I'll assume the latter. Here's an (untested) state machine that should give you a good start. It keeps track of whether water was already seen, when it started, and whether it is seen now. There is some redundant switching of the LED; removing that (if desired) "is left as an exercise for the reader".

#define watersensor 8               //Grove water sensor to Arduino Digital Pin 8
#define led 4                      //Grove LED to Digital Pin 4

#define TWOMIN (2*60*1000L)

bool isWater, wasWater = false;    // true => currently/were seeing water
uint32_t WaterStart_ms = 0;        // time first saw water

void setup() {
  pinMode(watersensor, INPUT_PULLUP);  // pullup for testing w/a button
  pinMode(led, OUTPUT);
}

void loop()
{
  // Is there water?
  isWater = !digitalRead(watersensor);     // read sensor

  if ( isWater ) {
    if ( !wasWater ){
      // First water: note the time
      WaterStart_ms = millis();
      wasWater = true;
    }
    else {
      // Water continues; time to light LED?
      if ( (millis() - WaterStart_ms) >= TWOMIN )
        digitalWrite(led, HIGH);
    }
  }
  else {
    // No water; LED off
    wasWater = false;
    digitalWrite(led, LOW);
  }
  delay(300);
}

Update:

Added wasWater = true; at line 27. The delay(300) at line 40 isn't necessary. Ran correctly when I tested it with a button (also negative logic) for the sensor.

  the light lights up randomly.

See if your sensor gives solid responses (try printing its output in loop() ). If it dithers around transitions, you may need to wait for some number of readings in a row that are opposite to the previous sensor state before you accept its new state as real.