How can an Arduino Mega 2560+Wifi Shield 2.0 (SeeedStudio) receive data from database in a XAMPP server on my PC? I'm trying to connect my Arduino Mega via Wifi to my XAMPP server. My main objective is get a value from my database and store it on a variable in Arduino code. With this new variable I'll be able to control the rest of the program... So I need your help. Can someone give me advice?

I already tried every thing that I found on the internet but it just doesn't work.

I think that the simple way is to send a GET request to the server and read its response... But for some reason I can't send a GET request through...

I tested it on the browser directly and the value shows up, so I think that the server side is all right.

Here is my Arduino code:

#include <Arduino.h>
#include <SoftwareSerial.h>
#include "WiFly.h"
#include "HTTPClient.h"

#define SSID      "mySSID"
#define KEY       "myKEY"
#define AUTH      WIFLY_AUTH_WPA2_PSK
#define HTTP_GET_URL "http://192.168.1.80/xampp/training/send_data_db.php/?temp=0"

// Pins' connection
// Arduino       WiFly
//  2    <---->    TX
//  3    <---->    RX
SoftwareSerial uart(10, 11);
WiFly wifly(uart);
HTTPClient http;
char get;

void setup() {
  Serial.begin(9600);
  Serial.println("------- WIFLY HTTP --------");
  uart.begin(9600); // WiFly UART Baud Rate: 9600
  // Wait WiFly to init
  //  delay(3000);

  // check if WiFly is associated with AP(SSID)
  if (!wifly.isAssociated(SSID)) {
    while (!wifly.join(SSID, KEY, AUTH)) {
      Serial.println("Failed to join " SSID);
      Serial.println("Wait 0.1 second and try again...");
      delay(100);
    }
    wifly.save(); // save configuration,
  }
  Serial.println("\r\nTry to get url - " HTTP_GET_URL);
  Serial.println("------------------------------");
  while (http.get(HTTP_GET_URL, 10000) < 0) {
  }
  while (wifly.receive((uint8_t *)&get, 1, 1000) == 1) {
    Serial.print(get);
  }
  if (wifly.commandMode()) {
    Serial.println("\r\n\r\nEnter command mode. Send \"exit\"(with \\r) to exit command mode");
  }
}

void loop() {
  int c;
  while (wifly.available()) {
    c = wifly.read();
    if (c > 0) {
      Serial.write((char)c);
    }
  }
  while (Serial.available()) {
    c = Serial.read();
    if (c >= 0) {
      wifly.write((char)c);
    }
  }
}

And here is my PHP code:

<? php
include("./connection/database_connect.php");
include("./top_table.php");

if ((isset($_SESSION["ID"])) AND (isset($_GET["temp"]))) {
  $id = $_SESSION["ID"];
  $sql = "SELECT temp FROM perfil, client WHERE perfil.ID ='$id'";
  $consult = mysqli_query($connect, $sql);
  $result = mysqli_num_rows($consult);
  if (($result == 1)) {
    $person_data = mysqli_fetch_array($consult, MYSQLI_ASSOC);
    $temp = $person_data["temp"];
    header("HTTP/1.1" . " " . 200 . "OK");
    header("Content-Type: text/html; charset=UTF-8");
    header("Content-Length: 1112");
    header("Connection: close");
    header("/r/n");
    echo $temp;
  } else {
    //se user dosen't exist on data base
    header("Location: http://192.168.1.80/xampp/training/login.php");
    exit;
  }
} else {
  header("Location: http://192.168.1.80/xampp/training/login.php");
  exit;
}
?>

You should forget about the $_SESSION["ID"]; on PHP side, because you are working stateless without any session!
You should give a parameter for identifying your variable from arduino to php script - is this the temp=0? If so you need to exchange

$sql="SELECT temp FROM perfil, client WHERE perfil.ID ='$id'";

with

$sql="SELECT temp FROM perfil, client WHERE perfil.ID =" . $_GET["temp"];

assuming that perfil.id is only an integer - if it is a string, then add "'".


DHT11 data in Arduino UNO to Firebase through ESP8266 Hello Good Day to Everyone.
I have a project where I need to send DHT11 sensor data to a Firebase database using both Arduino UNO and Esp8266 esp-01 wifi module. Both of them must work together to send the data.

Arduino Code:

#include <dht.h>

dht DHT;

#define DHT11_PIN 7

void setup() {
// put your setup code here, to run once:
Serial.begin(9600);

}

void loop() {
 // put your main code here, to run repeatedly:
int chk = DHT.read11(DHT11_PIN);
Serial.print("Temperature = ");
Serial.println(DHT.temperature);
Serial.print("Humidity = ");
Serial.println(DHT.humidity);
delay(1000);

}

My arduino code is working fine. Now comes the part where I need to program the ESP8266 which I am really confused how to pass the data to the wifi module and send it to firebase. I tried to code some and this is my

ESP8266 Code:

#include <ESP8266WiFi.h>
#include <FirebaseArduino.h>
#include <DHT.h>

#define FIREBASE_HOST "test.firebaseio.com"
#define FIREBASE_AUTH "authcode"

#define WIFI_SSID "mywifi"
#define WIFI_PASSWORD "12345"

#define DHTTYPE DHT11
#define DHTPIN  7

DHT dht(DHTPIN, DHTTYPE);
float temp_f;
unsigned long previousMillis = 0;
const long interval = 2300;

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

WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.print("connecting");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
 Serial.println();
 Serial.print("connected: ");
 Serial.println(WiFi.localIP());

Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);

 }

void loop() {
delay(2000);
float h = dht.readHumidity();
float t = dht.readTemperature();
delay(50);
Firebase.setFloat("temp",t);
Firebase.setFloat("hum",h);
delay(1000);
}

I don't want my esp8266 to go stand alone. I wanted the data to come from the arduino but somehow I don't know how to receive the data from the arduino in the esp8266.

I hope someone can enlighten me..
thank you

First of all, FirebaseArduino.h library is for ESP8266 itself and not for Arduino UNO.
The code you have written will not work as you are giving instructions like Firebase.setFloat("temp",t); to UNO. It will not compile.
What you should do is set ESP8266-01 as your primary board and let the UNO transmit the data by software serial.
ESP8266-01 will capture that data and transmit it over the Internet.
YOU CAN'T USE FirebaseArduino.h FOR ARDUINO UNO! It is for the ESP8266.
All YouTube videos will show you how to code for NodeMCU esp8266-12E. Do that for ESP-01 and communicate with Arduino for data (converting data calculated to string will help to reduce problems). Get data in form of string from UNO and transmit it using ESP-01!

If you want I can share all video list that I found useful!


Using Arduino as contact to the world for linux box if app crashes I am new to this micro controller thingie world so bare with me :)

Let me describe a scenario first.
Say I have a linux box for house automation embedded in a wall.
For security reasons is the only active access to the box the display mounted to the wall.

Another access would be via network and ssh but ssh is disabled.
Unfortunately does the web app sometimes crash and nothing goes. In the wake of that do I have to disassemble quite some stuff to get to the box and to revive it.

My Idea:
I can use a nfc or rfid sensor and hook it up to Arduino.
Would it be possible to make Arduino log on to the linux box and fire up and shutdown ssh?

I don't want to use Arduino Yun.
Is it achievable with an Arduino nano/Mega?

If not, which system would be your first choice to accomplish this task?

Thanks for your patience :)

I will put our comments together in an answer.

You are overthinking the security issue. In my opinion, using RFID to reset the system is a bigger security thread, than using ssh the correct way. Normal RFID chips are susceptible to spoofing (copying an existing chip). Also the intruder could remove the RFID module to directly access the communication lines (depending on how much you will have accessible of the extra hardware). Also you can of course use the Serial interface of an Arduino to execute shell commands on your machine. You need a program on the machine to read the input and execute the commands (Majenko mentioned agetty for this). But is that really the best way? Using an Arduino here is a very hardware-ry way of solving a software issue. It is overly complex to do things this way and there are better options.

Instead you should really just use ssh with key-based authentication (disable password authentication). You can limit the ssh daemon to the local network (though, if you don't have configured corresponding port forwarding in your router, it isn't reachable from the internet either way), or - if you really want the additional security - to one specific device in your network. With a normal ssh key (I think 2048 bit is the standard), brute forcing is not a viable option for intruders. If you keep your private key save, there is very very little chance, that an intruder can get past that. You can also save the private key only on an USB stick, which you only use for resetting the machine. Also you can limit the commands, that the ssh user can execute, to only the resetting (like only allowing rebooting).

Depending on your actual security needs, you can choose, how far you want to go. I personally would just use key-based ssh limited to the local network. That should be plenty enough security and would also give you the possibility to access the machine, that is running in your home easier.

Or, if you really don't want to open ssh for the machine, you can write a simple watchdog program, that can run on the machine. Since the webapp is failing, you can write a simple python program (or any other language you like), which is regularly loading the webapp (how exactly depends largely on the webapp and the exact type of failure - may be a simple HTTP GET request) to check, if it is still alive. If the liveliness test fails for a defined number of times (let's say 3), it will reboot the machine.

This method does not require any access to the machine, but you will have to develop the liveliness test. Writing the program is then really simple.

All that said, it is not a good sign, that the app fails that often. You didn't write, what app that is, and what exactly fails. Maybe you are able to fix that issue directly. Or the developer of the app can, so maybe raise an issue on his platform (where the project is hosted).


Using MQTT to send time stamp - to Arduino In previous question in this forum - I asked about updating clock on an ESP8266, using MQTT broker to send a time stamp on demand, in following manner:

1) ESP8266 sends a publish containing the payload :"sync",

2) broker answers in string format ( this part is python )

def on_message(self, client, obj, msg):
    self.arrived_msg = msg.payload.decode()
    if self.arrived_msg == "sync":
        a = datetime.datetime.now()
        b = "%d,%d,%d,%d,%d,%d,%d" % (a.year, a.month, a.day, a.hour, a.minute, a.second, a.microsecond) .  <------ here a string time format is created
        self.client.publish(topic=self.topics[0], payload=b, qos=self.topic_qos)

3) on a terminal (MAC OS), subscribed to relevant topic- cant see publish results. which are OK:

sync                           <----- ESP sends request
2018,9,18,12,44,18,903242      <----- string answer from broker

4) BUT when Arduino code get this time stamp:

void callback(char* topic, byte* payload, unsigned int length) {
        char incoming_msg[50];
        // ledBlink(30, 5);
        Serial.print("Message arrived [");
        Serial.print(topic);
        Serial.print("] ");
        for (int i = 0; i < length; i++) {
                Serial.print((char)payload[i]);  <----- print #1
                incoming_msg[i] = (char)payload[i];  <----- generate incoming msg
        }
        Serial.println("");

        if (strcmp(topic,clockTopic)==0) {       <------- detect relvant topic for clock sync
                Serial.print(incoming_msg);  <------ Print #2
        }

5) I get this result on serial monitor :

Message arrived [HomePi/Dvir/Clock] 2018,9,18,13,48,5,230009 <---- here time stamp is OK , Print #1
2018,9,18,13,48,5,230009$��?O: @ . <----- Print #2

EDIT1:

6) I tried adding a null termination in time stamp, but it just added \0 to time stamp
Appreciate any help

Guy

You forgot to set the terminating zero of the c-ctring incoming_msg.

add incoming_msg[length] = 0;


passing arrays via function returns wrong values I am trying to use the values of an array in some other function, but when I return via a function the contents is wrong.

This is the external function file I'm trying to use

#include "Arrayreturner.h"

Arrayreturner::Arrayreturner() { }

void Arrayreturner::setResults(int* res, int size) {
 int temp[size];

 for(int i=0;i<size;i++) {
  temp[i] = res[i];
 }

 results = temp;

}

int* Arrayreturner::getResults() {
  return results;
}

This is the header file

#ifndef ARRAYRETURNER_H
#define ARRAYRETURNER_H

#include <Arduino.h>
#include <Wire.h>

class Arrayreturner {
public: // some public definitions first

 Arrayreturner();

void setResults(int* res, int size);
int* getResults();
int* results;

};

#endif

And here is the main program

#include <Arduino.h>
#include "Arrayreturner.h"

Arrayreturner data;

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

}

int* returnArray(int arr[]) {
 // int arr[] = { 3, 5, 6, 7, 9 };
 int *p = arr;

 // Serial.print("rA: ");
 // for(int i=0;i<5;i++) {
 //   Serial.print(p[i]); Serial.print(" ");
 // } Serial.println("");
 return p;
}

Arrayreturner testfunc() {
 Arrayreturner data;
 int arr[] = { 2,4,6,8,10};

 data.setResults(arr, 5);

 return data;
}

void loop() {

  int arr[] = { 3, 5, 6, 7, 9 };
  // int *p = arr;
  // int (*ptr)[5] = &arr;

 // Serial.print("p: ");
 // for(int i=0;i<5;i++) {
 //   Serial.print(p[i]); Serial.print(" ");
 // } Serial.println("");

 // int* p1;
 // p1 = returnArray(arr);
 // Serial.print("p1: ");
 // for(int i=0;i<5;i++) {
 //   Serial.print(p1[i]); Serial.print(" ");
 // } Serial.println("");

 // data.setResults(arr, 5);

 // int* res = data.getResults();
 //
 // Serial.print("res: ");
 // for(int i=0;i<5;i++) {
 //   Serial.print(res[i]); Serial.print(" ");
 // } Serial.println(" ");

 Arrayreturner ar = testfunc();
 int* res = ar.getResults();
 Serial.print("res: ");
 for(int i=0;i<5;i++) {
   Serial.print(res[i]); Serial.print(" ");
 } Serial.println(" ");

 Serial.println("--------------");

  delay(2000);

}

There is probably something wrong with the pointer declaration, but I cant figure it out.

Thanks for the help

Your arrays are declared locally to the functions. You cannot return local arrays from a function - as soon as you return the arrays no longer exist.


How to use USB-in on an arduino? I'm trying to use an arduino as a controller adapter. How would I get USB-in to get the signal from a usb video game controller?

It makes actually no sense to plug an USB-Controller via an Arduino to a PC. The direct way and using an autofire/macro /custom key programmer app is more efficient.

The Arduino UNO (with 32u4) can either replace an USB controller as demostrated in NicoHood HID library or
additionally act as an interface for controller with strange vendor specific plugs demostrated in UNOJOY and you can build your own Controller/interface out of nearly every old non usb controller by cutting the hardware specific plug (e.g. old Xbox) and attach to an UNO who acts as "interface" to the PC. Another example is a C64-Joystick to the PC
The other option for using an Arduino is interfacing with "old video game systems" . For some there are already more or less succesfull projects. When connecting the USB controller via an USB shield you have normally a high lag time due to the USB shield library, so the better approach is to cut the USB plug and directly interface with the Arduino.

Project with USB Host-shield:

C64 - with USB Joysticks

Project old Joystick to USB-PC:

NES controller to PC USB

Project Arduino as controller for NES/SNES:

UNO to NES/SNES

Info on the pinout/protocol cn be found in this page


How can I communicate Raspberry Pi and Arduino (in both ways) using a 10-15m distance wires? I am starting a personal project of home automation and I have a raspberry pi and an arduino Uno board.

I want communicate raspberry pi and my arduino where my raspberry should be able to write and read signals to and from arduino.

The distance between them I think its going to be something around 10 to 15 meters.

What do I need for it? what kind of wires or other components I'll need to achieve my goal? I repeat: I do not want to communicate raspberry pi and arduino wirelessly.

Thanks!

for length such as this, you should be using protocols that are designed for length, such as:

UART,
CAN,
Ethernet

for UART, you can't of course use a direct connection between the two boards, you need to upgrade the connection and wiring to either rs232 or rs485, using a driver between the arduino pins and the cable.

Though, the simplest solution would be to plug the Arduino on the Raspberry Pi using a lengthy USB cable (or more likely 3 five meters cable), which should work fine as long as you only do serial communication. The USB 2.0 limitation of 5 meters are for "hi-speed" connections, which is not our concern for simple serial data communication.

HTH


How to switch between multiple BMP180 sensors? I have six BMP180 sensors for measuring temperature and pressure. The problem is that I can get the value from one sensor but I need values from all six sensors using a single Arduino Mega board. How can I do that? I have already tried powering each sensor with digitalWrite but that didn't work. If you have a solution, can you also provide the code for that?

The BMP180 uses the I2C bus and you cannot simply turn off the device, since that can block the I2C bus. Also it has only one, not changeable address. Thus you would need one I2C bus for every BMP180.

So know you have 2 ways to go:

You could use a Software I2C library and define one I2C port for each BMP. That would use 12 digital pins and you need to find a fitting library, that supports multiple instances. Due to the timed nature of the I2C bus, you most likely will only be able to service one bus at a time.
You could buy a multiplexer chip for both signal lines. Then you could switch the SCL and SDA lines to each BMP. For that you need the multiplexer chips, 2 pins for I2C and 3 digital pins for input of the multiplexer chips (assumes an 8-channel multiplexer)


Wi-Fi Module communication? I bought a Arduino Wi-Fi Module it does not have any manual or catalog

my project is to turn on/off a motor wireless

 it is working grate for the serial/usb cable but i couldn't make it work for wireless/wifi

after some walking around i found that my wifi module is making a wifi network called "HL-link_A49D"
with password from 1-8 and after network scanning i found that the module ip is 192.168.16.254/ username and pass are admin/admin
here is what i found

my question is how could i connect to the wifi module and send commands to it ?

Good detective work so far!
In the admin page you found one can see the name of the module: HLK-RM04. Googling on that I found the manufacturer/seller page.

A PDF with some information can be found here.

Also one link with somebody's experience with the module.

For other projects you might want to try as well the ESP8266 - very cheap and seems a lot of people have experience with it, so you might find more information on the net.


AutoConnect module does not broadcast SSID on ESP32 Dev Board This is my first post so I apologize if I'm missing all required info about my Arduino setup.  I'm a little new to this type of development.

Arduino 1.8.9

ESP32 Dev Module on /dev/cu.SLAB_USBtoUART

Mac OSX High Sierra 10.13.

I'm using the AutoConnect by Hieromon Ikasama v1.1.3 library to create an access point (AP), but the SSID (network name) is not being broadcasted even with the simplest code example.

Why isn't "ESP-78e9" showing up in my network list on my MAC or iPhone?

⸮⸮⸮8Y8⸮
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 0 - WIFI_READY
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 14 - AP_STOP
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 2 - STA_START
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 2 - STA_START
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 2 - STA_START
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 2 - STA_START
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 2 - STA_START
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 2 - STA_START
[E][Preferences.cpp:38] begin(): nvs_open failed: NOT_FOUND
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 4 - STA_CONNECTED
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 7 - STA_GOT_IP
[D][WiFiGeneric.cpp:381] _eventCallback(): STA IP: 192.168.1.192, MASK: 255.255.255.0, GW: 192.168.1.1
WiFi connected: 192.168.1.192 on ESP-78e9

Full code sample below, written with the Arduino IDE

#include <WiFi.h>
#include <WebServer.h>
#include <AutoConnect.h>

WebServer         Server;
AutoConnect       Portal(Server);
AutoConnectConfig Config;

void rootPage() {
  char content[] = "Hello, world";
  Server.send(200, "text/plain", content);
}

void setup() {

  Config.apid = "ESP-" + String((uint32_t)(ESP.getEfuseMac() >> 32), HEX);
  Config.psk = "Password1";
  Portal.config(Config);

  delay(5000);
  Serial.begin(9600);
  Serial.println();

  Server.on("/", rootPage);
  if (Portal.begin()) {
    // Serial.println("WiFi connected: " + WiFi.localIP().toString());
    Serial.println("WiFi connected: " + WiFi.localIP().toString() + " on " + Config.apid);
  }
}

void loop() {
    Portal.handleClient();
}

I've tried looking into why "nvs_open failed: NOT_FOUND" is occurring as that feels like the next step, but can't find any information on how to fix it.

I've also tried this on two boards of the same model.

Any ideas?

** Update **
I've modified the code to include the following, but still no AP and captive portal.

https://hieromon.github.io/AutoConnect/advancedusage.html#on-demand-start-the-captive-portal

According to the link above, that SHOULD start a captive portal before attempting to connect to WiFi.

  Config.autoRise = false;
  Config.immediateStart = true;

Instead I get the debug text here:

[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 0 - WIFI_READY
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 2 - STA_START
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 14 - AP_STOP
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 14 - AP_STOP
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 0 - WIFI_READY
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 14 - AP_STOP
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 14 - AP_STOP
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 14 - AP_STOP
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 14 - AP_STOP
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 14 - AP_STOP
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 2 - STA_START
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 2 - STA_START

Update 2

There may be a bug in the documentation.  I changed "autoRise" to true and the SSID was broadcasted.

  Config.autoRise = true;
  Config.immediateStart = true;

It looks like your ESP32 is already successfully connecting to an access point as a STA (station) and does not start its own Access Point (AP). You probably have already previously configured an SSID and password and the ESP32 is successfully reusing those, so it will not start the Captive Portal (as its own AP).

You should force AutoConnect to start up the Captive Portal or to forget its pre-programmed SSID and password. This can be achieved by On-demand starting of the Captive Portal like described on this page. According to the documentation you should put the following lines in your code (I have not tested this myself):

Config.autoRise = true;
Config.immediateStart = true;
Portal.config(Config);
....
Portal.begin();

NOTE: The documentation actually states Config.autoRise = false but it seems this does not have the desired effect.


Protecting variables and functions within a library that has no class If you want to have functions within a library that only the library itself should be able to use or variables that shouldn't be accessed from outside, you usually make them private by writing this in the header file:

class Lib{
  public:
    // All these can be accessed from outside
    void function1();
    void function2();
    int someNumber;
  private:
    // These two can't be accessed from outside
    void secretFunction();
    int secretNumber;
};

My question is this:

I want to write this library without using classes. How do I protect things from being accessed from anywhere in this case?

If your library is implemented in a single .cpp file, you can define these
variables and functions within that file, and give them the static
qualifier:

static int my_private_variable = 42;

static void my_private_function()
{
    ...
}

Obviously, there should be no mention of them in the .h file.

Note also that we are talking about global variables. Local variables
are already hidden within the defining function.


The importance of I/O pin DC current I am thinking about buying Arduino or Raspberry Pi.  I generally know Arduino advantages (fast start-up, low consumption, ADC converters) and disadvantages (low memory, low connectivity, hard programming), but I simply cannot figure out maybe the most important issue: current output for controlling devices.

One of the common cited advantages of Arduino system compared to Raspberry Pi system is that power per I/O pin is much larger.  Arduino Uno allegedly has up to 20 mA @ 5 V per pin and 50 mA @ 3.3 V per pin making quite substantial power of 0.15 W, compared to say typical 10 mA @ 5 V per pin for Raspberry Pi (although there is no official number available).

On the other hand

this power is far too low to control any motors and you still have to
provide shields,
new version Arduino 101 reduced that current to 20 mA and even less for some other Arduino models.

So, what is really the importance (if any) of these higher currents for home projects, compared between different Arduinos themselves and compared to Raspberry Pi?

There is also a question of total current for all pins together, which is also limited, but it is soooooo difficult to get official limits (for both Arduino and Raspberry Pi).

Please give me some insight into this issue, so I can decide.

The simple answer is: It doesn't matter.

Both Arduino and the Raspberry Pi, and every other common microcontroller board, are designed to control things, not provide power to things.

Digital IO pins aren't designed to drive heavy loads. Yes, some (like the Arduino) can provide slightly more current, but that is really unimportant for most projects.

Yes, some boards have more powerful power supply circuits on them so you can draw more current from their power supplies, but again that is largely irrelevant.

The one thing that you seem to be forgetting (or haven't realised) is that the microcontroller board does not have to supply all the power.

The Arduino, Pi, Teensy, chipKIT, whatever, is merely a controller. If your system needs more current it is up to you to provide that current. The Arduino etc merely controls the circuit or device that it is connected to.

It is very common to have multiple power supplies in a large project - each providing different voltages, or being used for different specific tasks within the project.

Just one thing you need to remember: Connect the grounds.


How to simulate Arduino? QUCS is the only open source software which offers simulation (and designing PCB layout [in future]) of electrical circuits. But the problem with QUCS is that it is under development and many important features are not yet available in it.

I want to simulate Arduino Uno board in it for my circuit. Does anyone know how to simulate Arduino or any other micro-controller in it?

P.S. Also any other open source software for simulation and PCB designing?

Simulating a microcontroller's program is common, but not as part of a circuit, unless you're into Systems on Chips.

Model the micro interfaces and simulate the peripherals separately

Analog systems cannot be modelled accurately by hand calculations alone, therefore simulation is often a necessary step (on top of that, real circuits might behave differently from the model). Non-programmable digital systems are deterministic in their behaviour, but only if the interfaces are correct - tight specifications on impedances and such often mean simulation is required here as well. Generally speaking, for both simulation becomes a must when the system is not dead simple. Microcontrollers on the other hand are sufficiently deterministic not to require any simulation: they do what they're told, except in very very very rare cases (single event upsets from radiation for example). Now, what they're told might allow glitches to happen, but that's a different story*. Therefore, usually the analog, or digital circuits around a microcontroller would be given equivalent interfaces based on the microcontroller's behaviour and physical specifications, and simulated separately.

*: As the code becomes more and more complex, it gets more and more difficult to follow what the microcontroller might do. Unexpected glitches may arise from e.g. concurrent access (though I can't say this is common in the micro realm), or insufficient resources (that is why dynamic allocation [malloc,new] are highly discouraged, so that the resources allocation is known at compilation time) etc. That's usually why tests are required, and step-by-step debugging is used as a means to locate any error that arises. But inherently, microcontrollers are highly predictable and except in certain cases, it is not worth it to go through simulation (do not mix up simulations and tests, tests are always required!).

Advantages of microcontroller simulators

However, microcontrollers simulators do exist. They are particularly helpful to watch what happens inside the microcontroller when the code executes step by step: call stack, watches on variables, interrupt vectors etc. This can also be done on the actual hardware using in circuit debuggers, but simulators are cheaper and are also good to save on EEPROM erase/write cycles and to avoid damaging your micro if you are afraid that the devices around it might be incorrectly configured (some controllers are very expensive, especially if they are qualified for medical, military or aerospace applications). I have seen such ICD's and simulators for Microchip PICs (MPLABX), but there must be equivalents for AVR (the micro which is on the Arduino's), or perhaps even integrated in an arduino-friendly environment (though I doubt it). You might want to take a look here.

If you've got deep pockets: mixed signal simulators

Finally, there are mixed signal simulators which allow you to simulate analog, programmable and non-programmable digital circuits alike; one component will have an analog SPICE model, another a VHDL model, and ADC/DAC blocks will be added automatically by the simulator between those devices depending on the logic input/output technology you specify. Those are extremely expensive (the one I used is Cadence Virtuoso), you don't want to do that unless you're doing an integrated circuit or something critical.

P.S: DesignSpark PCB v3 has LTspice in it. Never tried that feature in there though, I used to use LTspice directly.

Note that your opening "QUCS is the only open source software [...]" is wrong. There are plenty of simulators out there which are open source. I agree QUCS is a very user-friendly one though.


Read from serial monitor till timeout Is is possible to read from serial window till timeout?

Actually, what I am looking for is a function that reads from serial monitor, and if no data is available in serial monitor, then it should wait for some time and if still no data is arrived it should return.

Something like,

Serial.read(int timeout);

Use this:

byte x;
if (Serial.available() > 0) {
  x = Serial.read();
  }

This doesn't block, because you only read when there is something available in the input buffer.

Now, if you want to read an integer with time-out the serial input, this is a short demo:

#define TIME_OUT 10000L
void setup()
{
    Serial.begin(9600);

    while(!Serial);

    Serial.println();

    Serial.println("Input an int (waiting for 60 seconds");
}

void loop()
{
    static unsigned long timeLastInput = 0;
    unsigned long now = millis();
    static char buffer[10];
    static int index = 0;
    int value;

    if(Serial.available() > 0) {
        char x = Serial.read();
        timeLastInput = now;

        if(isDigit(x)) {
            buffer[index++] = x;
        } else {
            if(index > 0) {
                buffer[index] = 0;
                value = atoi(buffer);
                Serial.print("Integer=");
                Serial.println(value);
                index = 0;
            }
        }
    }

    if(now - timeLastInput > TIME_OUT) {
        Serial.println("Time out");
        index = 0;
        timeLastInput = now;
    }
}

It works by reading all digits into buffer. A non digit input signal the end of the integer. We use atoi to convert the integer ascii representation in his binary value. The result you wants is stored in the value variable.

Note that we read only one char at the time in each loop pass.

And this how the output looks:

And remember: code doesn't manage any error condition; is up to you.


Reading the audio signal from a smartphone i want to read the audio signal from my smartphone.
Can i just cut a headphonewire and connect it to the analog in? (Arduino uno)
I sadly dont know much about electronics.

greetings

No. It partly depends on the phone, but most put out a low voltage AC signal. This would drive the Arduino inputs negative. You can do this by biassing the input at the mid point (+2.5V) and feeding audio in via a capacitor. There are many projects which use similar to record audio.

PS I would not recommend cutting a headphone cord. The wires are very fine, and almost impossible to solder. If you want to do this make a custom cable.


Arduino due dying after connection, gets hot I have an Arduino Due (made in Italy) which suddenly (after working nicely for some time) started a new behavior: If I connect it to my computer via USB it is recognized and connects. The "On"-led is turned on but gets darker within seconds until it's off and the connection breaks. This happens with both USB ports. The area around the usb ports gets hot and especially the "504L" next to the reset buttons. (I just have my finger to measure the temperature, so it could also be something else in this corner).

What could have happened to the board? And is there anything I can try to revive it?

Update:
@GuitarPicker: It's the object labelled "0105" in your image, so it's probably the F1 fuse. If I connect the top USB, F1 gets hot, if I use the lower usb, F2 is activated.

There is nothing connected to the board. Before that, I used it to send SPI commands where I might have connected some of the SPI pins in the 6 pin group.
The board is placed on wood, so there should be no external connection
No smoke or visible damage.

The "504L" is a 500mA polyfuse.  If more than 500mA is attempted to be drawn through the USB port it will get hot which causes the fuse to "trip".  When it cools down again it will "reset".

Why is too much current being drawn through the USB port?  Well, that's what needs answering to know just why your board is misbehaving:

Do you have lots of things plugged into the board - like LED strips, motors, etc?
Is the board sat on something metal causing a short circuit? (I did that by having some loose change on my desk once).
Have you physically damaged the board and caused some pins of one of the chips to short together?
Has the Magic Smoke™ escaped from one of the chips rendering your board broken?


Limiting Data Output Frequency from ADXL345 I have a working ADXL345 connected to an Arduino UNO, I need to limit the rate at which the ADXL345 takes in readings. I am using the SparkFun library for this sensor. I have read about the delay function and it works in the loop function but I was wondering if there might be a better way that is much more efficient?

Everytime you get a value from the sensor (for example with getX() or others) the library communicates with the sensor over I2C or SPI. So you can limit the usage of these function in your sketch. One way is with using delay(), but this is considered unefficient in most cases, since you are basically busy waiting during execution of delay(). You will not be able to do anything else in the future during this time span (if you want to add functionality to your device).

It's better to use non-blocking code, that only checks, if it is time to do something and if not going further through the program. Image like you yourself would bake a pizza. You would not stare at the clock for 20 min, until the time is up. You would periodically check, if the time has come to take the pizza out.

You can achieve this on an Arduino with use of the millis() function, which returns the number of milliseconds since the last powerup/reset. (Note that it overflows after about 50 days). There are plenty of tutorials for that out there. You can start with the BlinkWithoutDelay example from the Arduino IDE, which perfectly shows, how this is to be coded.

Note: If you are using the sensor with a battery, then you might want to limit its power usage. For this the library can set the corresponding registers in the sensor to set the datarate in the sensor (The rate at which the data in the sensor is updated). A smaller rate will lower the power consumption. So you can set the rate at about the rate of the reading in your sketch.


Why is 8x8 matrix pins do not correspond to rows and columns order? It would be easier to program led matrix if 1-8 pins corresponded to 1-8 rows and 9-16 pins corresponded to 1-8 columns.
Instead there is the following arrangement:

Why is it made like this?

It's probably easier to manufacture, other than that, I don't see why.
If this is a serious issue, you can contact your manufacturer, since he is most likely to know why.

You can:

Work around the issue, by wiring pin 1 to input 9, pin 2 to input 14 etc.
Make a software solution like:

#define ROW1 9

#define ROW2 14
Buy an LED-matrix that has the pins in the correct order (check the datasheet before purchase).


Which board to select in PlatformIO for ESP Wroom 32? I'm quite new in this microcontroller topic and my next step is to make use of a wlan module, which is a ESP WROOM 32.
As IDE I'm using Visual Studio + PlatformIO and I can't figure out how to access the module. Atm I use these parameters:
[env:esp12e]
platform = espressif8266
board = esp12e
framework = arduino
monitor_speed = 74880

but I receive:
(...)
CURRENT: upload_protocol = esptool
Looking for upload port...
Auto-detected: /dev/ttyUSB0
Uploading .pio/build/esp12e/firmware.bin
esptool.py v2.8
Serial port /dev/ttyUSB0
Connecting......
Chip is ESP8266EX
Features: WiFi
WARNING: Detected crystal freq 20.45MHz is quite different to normalized freq 26MHz. Unsupported crystal in use?
Crystal is 26MHz
MAC: 00:08:ff:00:00:00
Uploading stub...
Running stub...

A fatal error occurred: Invalid head of packet (0x46)
*** [upload] Error 2
============================================================================= [FAILED] Took 3.27 seconds =============================================================================
The terminal process "platformio 'run', '--target', 'upload'" terminated with exit code: 1.

edit:
The ESP WROOM 32 is a NodeMCU 32 and the board config now is:
[env:espwroom32]
platform = espressif32
board = nodemcu-32s
framework = arduino
monitor_speed = 115200

and to check if everything works:
void setup() {
  pinMode(2, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(2, HIGH);
  delay(1000);
  digitalWrite(2, LOW);
  delay(1000);
}

I also had problems that I received Failed to connect to ESP32: Timed out waiting for packet header nevertheless but here is a nicely explained workaround for that. Solution is, either you hold the BOOT button pressed while uploading the code or you sold a capacitor to specific pins on the board.
I just tried to hold the boot button and it's blinking now. Finally :)
I'm sure, a lot of further issues are only waiting on the way ^

The ESP WROOM32 is an ESP32, not an ESP8266. You have PlatformIO configured for an ESP8266, specifically the ESP12e, and there's no way that's going to work.
You'll want something more along these lines:
[env:espwroom32]
platform = espressif32

To choose the board - if you're using a breakout board, you'll need to be more specific about it - what model is it? ESP WROOM32 is just the name of the CPU module; PlatformIO needs to know the size of the flash storage in order to upload properly. Your link is to the entire Espressif ESP32 site. Otherwise, look through PlatformIO's list of ESP32 boards and find one that matches the amount of flash storage your board has.
You might want to read PlatformIO's ESP32 documentation.


where does access point's IP address come from for sketch AP_SimpleWebServer.ino in Github WiFi101 examples I don't understand where the access point's IP comes from.
Sketch uses WiFi.beginAP( ssid )   ..to start the AP.
Then, printWifiStatus() gets the access point's IP with:

IPAddress ip = WiFi.localIP();

How does .beginAP() create the IP?  What does it use for a mask?

I'm creating network service on a MKR1000, and want to use .beginAP() to make it an access point, so I don't need a "middle man" (router).  Going to have mobile device (iPhone) connect directly to Arduino MKR1000.

If you look into that github source code, you can see startAP function and mainly rows with strM2MAPConfig.au8DHCPServerIP:

uint8_t WiFiClass::startAP(const char *ssid, uint8_t u8SecType, const void *pvAuthInfo, uint8_t channel)
{
    tstrM2MAPConfig strM2MAPConfig;

    if (!_init) {
        init();
    }

    if (channel == 0) {
        channel = 1; // channel 1 is the minium channel
    }

    // Enter Access Point mode:
    memset(&strM2MAPConfig, 0x00, sizeof(tstrM2MAPConfig));
    strcpy((char *)&strM2MAPConfig.au8SSID, ssid);
    strM2MAPConfig.u8ListenChannel = channel - 1;
    strM2MAPConfig.u8SecType = u8SecType;
    strM2MAPConfig.au8DHCPServerIP[0] = 0xC0; /* 192 */
    strM2MAPConfig.au8DHCPServerIP[1] = 0xA8; /* 168 */
    strM2MAPConfig.au8DHCPServerIP[2] = 0x01; /* 1 */
    strM2MAPConfig.au8DHCPServerIP[3] = 0x01; /* 1 */

    if (u8SecType == M2M_WIFI_SEC_WEP) {
        tstrM2mWifiWepParams* wep_params = (tstrM2mWifiWepParams*)pvAuthInfo;

        strM2MAPConfig.u8KeyIndx = wep_params->u8KeyIndx;
        strM2MAPConfig.u8KeySz = wep_params->u8KeySz;
        strcpy((char*)strM2MAPConfig.au8WepKey, (char *)wep_params->au8WepKey);
    }

    if (m2m_wifi_enable_ap(&strM2MAPConfig) < 0) {
        _status = WL_CONNECT_FAILED;
        return _status;
    }
    _status = WL_AP_LISTENING;
    _mode = WL_AP_MODE;

    memset(_ssid, 0, M2M_MAX_SSID_LEN);
    memcpy(_ssid, ssid, strlen(ssid));
    m2m_memcpy((uint8 *)&_localip, (uint8 *)&strM2MAPConfig.au8DHCPServerIP[0], 4);
    _submask = 0x00FFFFFF;
    _gateway = _localip;

    // WiFi led ON (rev A then rev B).
    m2m_periph_gpio_set_val(M2M_PERIPH_GPIO15, 0);
    m2m_periph_gpio_set_val(M2M_PERIPH_GPIO4, 0);

    return _status;
}


uint8_t * to integer and string Convert text array/buffer to integer and string.

hi! i'm sending text to an arduino and the output of that library is a
uint8_t array.

Atm the text send is a number between "0" and "1023"

void something(uint8_t * text){
 analogWrite(13,text);// does not work
}
/*
toInt() also not
int() not
atoi() not
invalid conversion from 'uint8_t* {aka unasigned char*}' to 'const char*'
*/

i need to convert it to an  integer or better to a uint16_t.

As i plan to send custom commands in near future it would also be good to know how to convert that array to a string, that i then split/manipulate/parse.. whatever.

i looked in various posts but i couldn't get it to work on that simple example above. i'm new to c++

if it's needed the length is also aviable inside the function.

Your problem is that you are storing your text in an unsigned pointer (uint8_t *)instead of a signed pointer (char *).

If you change all your text types to char * then you can directly use atoi().  If you have a lot to change, though, you can just cast the unsigned pointer into a signed one (and make it const at the same time):

analogWrite(13, atoi((const char *)text));


Ultrasonic distance module works without connecting to gnd I have a (HCSR04) ultrasonic distance module connected to arduino , i have connected all the four pins of the module properly and its working fine , then when i pull off the wire which is connected to ground in arduino , the module works totally fine . How the module works without connecting its ground pin to arduino ground ?

It's not uncommon for part to "sort of" work when one of the supply rails is missing and an input signal of the some polarity somewhat substitutes for it, often through built-in ESD protection diodes.  In this case, the trigger input when idle is low, and there's probably some capacitance on the board that could hold it through the brief trigger pulse.

It's a bad idea to rely on this though, both as it typically means stressing parts by operating them outside of specified limits, and can also produce not-quite reliable behavior.

For example, I once wired an SPI flash chip on a small carrier stuck underneath an MCU eval board, in order to test some software for a board I was designing.  It worked great.  Or I should say, it did right up until I tried to write to it, which would always fail.  Eventually I discovered that I'd forgotten the ground connection when wiring it up.  It was able to return enough current through the I/Os to perform read operations, but not to support a write.


Is this the right way to blink a character on LCD? The code is this:

#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27, 16, 2);

unsigned long blinkTime = 0;
int ValueA = 22;
String placeHolder = "  ";

void setup() {
  lcd.begin();
}

void loop() {
  lcd.setCursor(7, 0);
  if (millis() - blinkTime > 2000) {
    lcd.print(ValueA);
    blinkTime = millis();
  }
  if (millis() - blinkTime > 1000) {
    lcd.print(placeHolder);
  }
}

The I2C LCD library have a lcd.blink() function but it seems that only blinks a "cursor".

The problem with above code is the placeHolder, what if ValueA gets bigger than 2 digits?

Is there a better way to blink a value on LCD?

To blink a number (alternate between the number and empty space(s)), you could try the BlinkLCD class in this sketch. It only works with numbers from 0 to 4294967295 or text (char array, 16 characters max). It does not work with floating point numbers.

// 4540 bytes.
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27, 16, 2);

class BlinkLCD{

  private:

    byte m_blinkState, m_startPosition, m_dataLength;
    unsigned long m_dataToBlink, m_previousMillis, m_blinkRate;
    char m_text[16 + 1];

  public:

    BlinkLCD(): m_blinkState(0), m_startPosition(0), m_dataLength(0),
                m_dataToBlink(0), m_previousMillis(0), m_blinkRate(500),
                m_text(){}

    void Update(){

      unsigned long m_currentMillis = millis();

      if(m_currentMillis - m_previousMillis >= m_blinkRate){

        byte m_row = 0;
        m_blinkState = !m_blinkState;
        m_previousMillis = m_currentMillis;

        if(m_startPosition > 15){
          m_startPosition -= 16;
          m_row = 1;
        }

        lcd.setCursor(m_startPosition, m_row);

        if(m_blinkState){
          if((unsigned)strlen(m_text) > 0){
            lcd.print(m_text);
          }
          else{
            lcd.print(m_dataToBlink);
          }
        }
        else{
          for(byte i = 0; i < m_dataLength; i++){
            lcd.print(" ");
          }
        }
      }
    }

    void SetBlinkRate(unsigned long blinkRate){
      m_blinkRate = blinkRate;
    }

    void SetNumber(unsigned long dataToBlink){
      m_dataToBlink = dataToBlink;
    }

    void SetLength(byte dataLength){
      m_dataLength = dataLength;
    }

    // LCD top row, columns 0 - 15
    // LCD Bottom row, 16 - 31
    void SetStartPosition(byte startPosition){
      m_startPosition = startPosition;
    }

    void SetText(char text[]){
      strcpy(m_text, text);
    }

};

BlinkLCD TopRowLCD;
BlinkLCD BottomRowLCD;
BlinkLCD BottomRowLCDtext;

void setup(){
  lcd.init();
  lcd.backlight();
  lcd.clear();
  lcd.print("Temperature 35 C");
  lcd.setCursor(0, 1);
  lcd.print("Num = 4294967295");
}

void loop(){

  // Simulate sensor data.
  static byte counter = 35;
  static unsigned long previousMillis = 0;
  unsigned long currentMillis = millis();

  // Update the temperature reading every 2 seconds.
  if(currentMillis - previousMillis >= 2000){
    previousMillis = currentMillis;
    counter++;
    if(counter > 45){counter = 35;}
    lcd.setCursor(12, 0);
    lcd.print(counter);
  }

  // Blink the temperature reading if it's over 40 C.
  if(counter > 40){
    TopRowLCD.SetNumber(counter);
    TopRowLCD.SetStartPosition(12);
    TopRowLCD.SetLength(2);
    TopRowLCD.SetBlinkRate(250);
    TopRowLCD.Update();
  }

  // Blink a number on the second row of the LCD
  // with a default blink rate of 500ms ON, 500ms OFF.
  BottomRowLCD.SetNumber(4294967295);
  BottomRowLCD.SetStartPosition(22);
  BottomRowLCD.SetLength(10);
  BottomRowLCD.Update();

  // Blink some text with at the default blink rate.
  BottomRowLCDtext.SetText("Num");
  BottomRowLCDtext.SetStartPosition(16);
  BottomRowLCDtext.SetLength(3);
  BottomRowLCDtext.Update();

}


Breadboard-to-Arduino wiring with flat flex cable assemblies? I want to wire Arduino Due connectors to a breadboard 8-at-a-time, so they're easier to remove and more reliable.

I tried these Flat Flex Cable Assemblies (FFC assemblies) terminated with "solder lugs" from Digi-Key, but the pins are just a little too short to penetrate the Arduino connectors well.  Similarly they barely reach into to the breadboard contacts, so they tend to fall out.  Anyone find a workable product for this?

This solution is good but requires a lot of manual soldering.  Looking for prepackaged.

Search for male-male jumper wire. Some of what you'll find is individual wires but there are also many that are connected together and you can rip off the width you need.

Here's one from Adafruit but there is no shortage of them on ebay/amazon.


read AM signal only with an Arduino Some people have managed to send simple AM signals with just a bare Arduino. An example is here.
This works thanks to the fact that the PWM can reach high frequencies and, setting the divider properly, it is possible to broadcast a 1337 kHz carrier over a short distance with just a wire acting as an antenna.
I know it's not that useful, but it's really nice as an educational tool.

I was wondering if it would be possible to apply the same concept, but for the receiver. For instance simply using a pulseIn() detection on a pin connected to an antenna. Would it be possible to detect the carrier, and, maybe, even demodulate a message, eg, in morse code?

If not, would just a adding an amplifier be sufficient? Any recommendations for the amplfier and the circuit?

Thanks very much for your suggestions.

AM (Amplitude Modulation) varies the amplitude of the carrier based on the input signal. So, assuming you had some circuitry (LC circuit) to receive a particular carrier frequency and managed to boost the voltage so that it was in the range 0-5v then you would able to feed this to an analog input on the Arduino.

AnalogRead requires around 100uS per sample, so your max sampling rate would be 10K/s, which might just cut it for voice (up to 3.4Khz, sampling at least 2 * the highest freq).

However, you then need to do something with the sample value (in code) and depending on how long that 'something' takes, your actual sample rate will be reduced.


How do I go about building a backend for my Arduino device? I am new to Arduino, but I am putting together a project in which the Arduino Uno has multiple sensors (temperature, humidity, etc) collecting data. Right now all it is currently going to do is get the data and send it over to https://plot.ly/ to save and view the data.

Using this: http://tronixstuff.com/2014/01/21/online-data-analysis-arduino-plotly/

What I want to do is build a backend application that will instead receive this data and actually do something with it. It would use users, and all the usual backend functionality. So either some good PaaS that someone can recommend, and/or resources of what to use to build out an API that can "talk" to an Arduino. Perhaps Python or Node (NO PHP), and it should do it via Wifi to connect to the internet.

Thank you

I use emoncms for much of my data processing along with node-red and MQTT all running on a RaspberryPi see Emoncms to get started


How can I send and receive data from an Arduino MEGA 2560 and Python? Hello community I am relatively new to the Arduino world and I am facing some issues trying to establish serial communication between the MEGA 2560 and Python using my PC, the desired result is to print the variable 'cnt' after in the code below in Arduino after communicating with Python, below are the codes I am using for the Arduino and in Python. [Note: I am using a PIR sensor(pin 4) that does trigger when an object is nearby and print the first statement on the serial monitor, so the issue is not there.]
Arduino:
int pin = 4; //Output pin of sensor
int cnt = 0; //Count variable after processing in Python
int dat = 0; //Variable to ensure data is being transmitted from Python to Arduino

void setup() {
  Serial.begin(9600);
  pinMode(pin, INPUT);
  pinMode(LED_BUILTIN, OUTPUT); //This output is here to ensure the code runs to the dat if statement and the data is received
}

void loop() {
    int pirsensor = digitalRead(pin);

    if (pirsensor == 1){
      Serial.println("Hello, there's data here in Arduino"); //String as an example bt you want to send the data of the ArduCAM using the serial port
         if (Serial.available()>0){
              dat = Serial.read() - '0';

              if (dat == '1'){
                    cnt = cnt + 1;
                    Serial.print("Count is equal to: ");
                    Serial.print(cnt);
                    digitalWrite(LED_BUILTIN, HIGH); //Turn on LED
                    }
              }

          }
}

Python code:
import serial

dat = serial.Serial('COM5',9600,timeout=1) #Serial object for communication
if (dat.in_waiting>0): #Conditional to verify if there is data in the serial port
    print('Hello')
    dat.write(1)
    print('Works')

Your problem is that you aren't sending the values from python in bytes. A more reliable way is to send the data in bytes like dat.write(b'1') and then receive it on the Arduino using Serial.readString(). I also had many issues with this and this is the best solution. "https://roboticsbackend.com/raspberry-pi-arduino-serial-communication/#:~:text=The%20easiest%20way%20is%20to,Arduino%20IDE)"
If not, you can use the I2C interface. Just be careful, the logic level if your Python is running on a Raspberry Pi.


How to append float value of into a string ? I have a float variable lng = 33.785469 and lat = 78.126548. Now can I convert them to String and append in a String variable "my_location" as "your location is \nlng = 33.785469 \nlat = 78.126548". I was trying to do this with

    char charVal[5];               //temporarily holds data from vals
    String stringVal = "";     //data on buff is copied to this string

    dtostrf(lng , 4, 2, charVal);  //4 is mininum width, 2 is precision; float value is copied onto buff
    //convert chararray to string
    for(int i=0;i<sizeof(charVal);i++)
    {
    stringVal+=charVal[i];
    }
    GPS_string = GPS_string + "Car location: \nlat:" + stringVal;
    stringVal = "";

and it given me an error :

error: cannot convert 'String' to 'double' for argument '1' to 'char* dtostrf(double, signed char, unsigned char,

This has been answered in the previous question but I can repeat it here:

void loop()
{
  ...
  float latitude = 33.546600;
  float longitude = 75.456912;
  String buf;
  buf += F("your location is \nlat:");
  buf += String(latitude, 6);
  buf += F("\nlong:");
  buf += String(longitude, 6);
  Serial.println(buf);
  ...
}

An alternative is to use dtostrf() as in your snippet:

void loop()
{
  ...
  float latitude = 33.546600;
  float longitude = 75.456912;
  const int BUF_MAX = 64;
  char buf[BUF_MAX];
  const int VAL_MAX = 16;
  char val[VAL_MAX];
  strcpy_P(buf, (const char*) F("your location is \nlat:"));
  dtostrf(latitude, 8, 6, val);
  strcat(buf, val);
  strcat_P(buf, (const char*) F("\nlong:"));
  dtostrf(longitude, 8, 6, val);
  strcat(buf, val);
  ...
}

Cheers!


How to compile, upload and monitor via the Linux command line? Interfacing an Arduino Uno (uploading etc.) with the Arduino IDE (using the Fedora package) works fine under Fedora 21.

But I rather want to use vim + make + vim-quickfix-mode etc.

How can I do that?

Preferably via the tools available from the Fedora repositories.

I assume that the IDE calls externals command line utilities for the uploading etc.

The equivalent to the IDE's serial monitor is probably connecting a terminal emulator (e.g. screen) to /dev/ttyACM0, right?

Perhaps there is a good example project one can look at the makefile?

I use the command-line interface to the arduino command.

I run it like this:

arduino --upload sketch/sketch.ino --port /dev/ttyUSB*

There is a page which describes other command-line tools, like inotool. That page also has an example Makefile. These alternatives seem enticing, but apparently, as of this writing, none of them work. I'm assuming this is due to some recent changes in Arduino IDE distribution files which they depend on.

Running arduino as above is a bit slow, because it has to load Java I guess, but at least it works. There is also an arduino-builder command that comes with the Arduino IDE distribution. As of this writing, it was not sufficiently well-documented for me to be able to figure out how to use it. For instance there are no example command lines in the README or in any of the tutorials I came across, and I couldn't figure out how to use it to upload code to the board. However, presumably it is able to give us a faster compile than arduino. The README also mentions being able to reuse object files from a previous compile, so there is some make-like functionality.

To view serial output I use something like

stty -F /dev/ttyUSB* 1000000 raw -clocal -echo
cat /dev/ttyUSB*

The number 1000000 should match the number you pass to Serial.begin() in your board code. You can also use screen if you have a board program which is appropriately interactive, or you can use whatever utility to write directly to the device. By the way, my Due shows up as /dev/ttyACM0 (rather than /dev/ttyUSB0 for the Uno).


Extracting .hex from Arduino Due I have an Arduino Due that was programmed by the Arduino IDE, to cut things short I lost access to the original sketch (.ino) file, there is no way of recovering it no matter what.
I know that in the 8-bit MCUs I can read the .hex file from the flash memory, I already did that with PIC and AVR MCUs with their software programmer utilities.
My question is: Can I use a software programmer utility on Windows PC to extract the hex file to reprogram other Arduino Due with it? If yes, please help me.
I've read about the Bossac utility, it looks promising, but I have no experience in the ARM MCUs field at all.
again: I am NOT interested in C or Assembly code, I just want the .hex file.

You can use JTAG and probably should.  But, it can also be done with bossac if you are very careful.  If you're not, you'll end up erasing your flash on your source board.
Using bossac
This would maybe not be preferred over JTAG because it is probably easier to screw up (see warnings below), but it can be done.  I may add some on JTAG programming later, and if I do it may be above this section for that reason.  The main advantage here is just that you don't need a JTAG programmer.  The one caveat is that your existing sketch, or rather the image of the sketch that has been burned onto what I'm calling the "source board" has to be functioning well enough that it can cooperate in being placed back into the ROM bootloader.  I fully expect this is not a problem for you, or for pretty much any normal Arduino sketch that has been burned to a board.
WARNINGS

Under NO circumstances do you want to connect to the PROGRAMMING port of your source board at 1200 baud.
Doing so will erase your board, and then that's the end of it.

In the below you will be connecting to the Native USB port at 1200, NOT the programming port.
Connect only one port at a time to your computer so there is no possibility of selecting the wrong one.

Practice this whole procedure with a board you don't care about first.

Locate your BOSSAC command.
On my Windows machine, it was in:
C:\Users\username\AppData\Local\Arduino15\packages\arduino\tools\bossac\1.6.1-ardunio\bossac.exe

It may be under a different version number.  It's possible that it will be in a completely different location.
cd %USERPROFILE%
dir bossac.exe /s/b/p/a

Should locate it it, eventually, in any case.
On Linux it will be under ~/.arduino15 somewhere:
find ~/.arduino15 -name bossac

On a Mac it will probably be under a /Library/ directory under the user account somewhere.  You get the idea, locate it, make sure you can run it.
NOTE: There's a bossa program that is the GUI version where bossac is a command-line program.  Unfortunately the IDE board support files don't ship the GUI program.  If you're having trouble with the command-line and want to try that instead, go for it.  But test it on a board you don't care about beforehand.  I have not tried it.
Connect to the Native Header
Connect your native USB port on the source board and only to that port.

Enable boot to ROM
Open a terminal emulator of your choice at a rate of 1200 baud to the native USB port, wait a couple seconds and then close the port.  You can use the Serial Monitor from the IDE to do this if you want:

Select the correct port from Tools/Port.

Open the Serial Monitor

Switch the baud rate to 1200 baud.

You're not going to type anything and you're not going to see anything once you're connected at 1200 baud.

Close the Serial Monitor

You probably should:

See if the port has changed COM#, if so select the new one.

Re-open the serial monitor

Change the baud rate again to anything-but-1200-baud

Close the serial monitor again.
This is not strictly necessary but the IDE remember the last chosen baud rate, and for what we're doing this is a slightly dangerous thing.

Close the IDE as well.

What connecting at 1200 baud does is activate the code inside the core part of the programmed sketch that changes the board to boot from the internal ROM bootloader.  It doesn't need traffic.  It just needs to see a request for 1200 baud.  More specifically, it needs to see the DTR "signal" go inactive, which happens when the port is closed, when the effective rate was 1200 baud.
NOTE: if you screw up here and connect to the programming port at 1200 baud instead, you'll wind up causing the ATMega16U2 to erase your source board.  The IDE remembers your last chosen baud rate, which makes this easy to screw up as well.  Hence the weird little dance in the above instructions regarding reopening the serial monitor and changing to something other than 1200 baud.  It's just putting an extra barrier up to accidentally doing this.
Once you've connected to the native USB port at 1200 baud and closed the port, your board will not run your sketch any more.  It's still there, it's just not running it.  The board has been told to sit in the ROM based bootloader, waiting for bootloader commands.
Saving your existing sketch's image
What we're going to do is run the bossac command you found earlier like so:
bossac --read saved-sketch-image.bin --boot --reset

I'm assuming you either changed directory to where bossac.exe is, or alternately you're going to specify the necessary path to it found earlier.  I've found this command locates the correct COM port automatically.
This command:

Downloads all of flash, 512 kbyte, and takes while, 128 seconds in one test.  Weirdly the same version under Linux takes closer to 10 seconds;  I haven't looked into why the difference, but I'm also unconcerned.
So you now should have a 512 kbyte raw binary file containing your sketch image.

It re-enables the boot-from-FLASH so that on the next reset it will go back to running your sketch

It resets your board, so it will begin running your old sketch.  If you don't want it to do that until you power cycle it, you could just as easily leave off the --reset part.

As said, this is a raw binary file.  But you mentioned a HEX.  I'm assuming you didn't mean that literally, so I'm not going to detail how to convert the .bin file to a HEX format.  Though, if you want to do that, you should know that it needs to be offset to 0x80000, because that's where flash starts on the Due.
Disconnect your source board from USB.
Making your clone (target) board
Connect to your target board via the programming port.

Hold the erase button for a few seconds to make sure the target board is erased.  Usually this would be done by the IDE connecting to the port for a while at 1200 baud.  But since we're using bossac at the command line, we need to do that step manually; it's just easier to use the button this time.

Reset the board with the reset button.  Your target board is now sitting in its ROM bootloader awaiting commands.

Put your image on the new board with:

bossac --write saved-sketch-image.bin --boot --reset

Again, it's programming the whole 512 kbytes.  In one test on Windows it took about 100 seconds; no difference between Windows and Linux.  We're using the USART (programming port) which is slower than USB and we're flashing rather than reading which is slower; I haven't bothered to figure out which thing is the bottleneck.

Like before --boot sets the board to boot from flash (your sketch) on next reset.

And again --reset just resets the board.

Your target board should now be be behaving identically to the original source board.


Does the tone() generates unwanted signal? I was trying to use the tone function for another project but I found that it also generates an undesired frequency (not the harmonics above of square wave it generates) but a lower frq square wave. Is this normal or somethings wrong with my implementation?
the code is pretty simple:

void setup()
{
    pinMode(7,OUTPUT); //set the pin as output
    tone(7,10000); //start a 10KHz tone
    while(true); //stay here
}

void loop()
{ }

hardware was an Uno also tried different pins above but same results. first I tried a 470R and an 8R speaker. then guess maybe the inductance, or something else causing it so I used a piezo buzzer as seen below:

Pin(x)--->10KR--->piezo--->GND

however it was the same. I measured the lower frequency as 19.55Hz for a tone(10000) and 39.05Hz for tone(40000); both are pretty annoying.
what causes this and whats the workaround?

I could reproduce the problem with the posted code. This will be caused by the fact that the tone library uses interrupts and has to manually toggle pins, which will always have a bit of jitter. You are better off setting up a hardware timer to generate the tones, this does not require interrupts.

For example:

#include <TonePlayer.h>

TonePlayer tone1 (TCCR1A, TCCR1B, OCR1AH, OCR1AL, TCNT1H, TCNT1L);  // pin D9 (Uno), D11 (Mega)

void setup()
  {
  pinMode (9, OUTPUT);  // output pin is fixed (OC1A)

  tone1.tone (10000);  // 10 kHz
  }

void loop() { }

This uses a fairly small library I wrote, which you can download from http://www.gammon.com.au/Arduino/TonePlayer.zip

Library code

If you don't want to trust some zip file from a random web site, here is TonePlayer.h:

/*
 Play tones with hardware timers
 Author: Nick Gammon
 Date:   1 April 2013
*/

#include <Arduino.h>

class TonePlayer
  {
  // addresses of output ports - NULL if not applicable
  volatile byte * const timerRegA_;
  volatile byte * const timerRegB_;
  volatile byte * const timerOCRH_;
  volatile byte * const timerOCRL_;
  volatile byte * const timerTCNTH_;
  volatile byte * const timerTCNTL_;

  public:
    // constructor
    TonePlayer (
          // ports
          volatile byte & timerRegA,
          volatile byte & timerRegB,
          volatile byte & timerOCRH,
          volatile byte & timerOCRL,
          volatile byte & timerTCNTH,
          volatile byte & timerTCNTL)
       :
         timerRegA_  (&timerRegA),
         timerRegB_  (&timerRegB),
         timerOCRH_  (&timerOCRH),
         timerOCRL_  (&timerOCRL),
         timerTCNTH_ (&timerTCNTH),
         timerTCNTL_ (&timerTCNTH)
  { }

    void tone (const unsigned int Hz);
    void noTone ();

  };  // end of TonePlayer

/*

 PERMISSION TO DISTRIBUTE

 Permission is hereby granted, free of charge, to any person obtaining a copy of this software
 and associated documentation files (the "Software"), to deal in the Software without restriction,
 including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
 and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
 subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 LIMITATION OF LIABILITY

 The software is provided "as is", without warranty of any kind, express or implied,
 including but not limited to the warranties of merchantability, fitness for a particular
 purpose and noninfringement. In no event shall the authors or copyright holders be liable
 for any claim, damages or other liability, whether in an action of contract,
 tort or otherwise, arising from, out of or in connection with the software
 or the use or other dealings in the software.

 */

And here is TonePlayer.cpp:

/*
 Play tones with hardware timers
 Author: Nick Gammon
 Date:   1 April 2013
 */

#include <TonePlayer.h>

void TonePlayer::tone (const unsigned int Hz)
{
  // it takes two toggles for one "cycle"
  unsigned long ocr = F_CPU / Hz / 2;
  byte prescaler = _BV (CS10);  // start with prescaler of 1  (bits are the same for all timers)

  // too large? prescale it
  if (ocr > 0xFFFF)
    {
    prescaler |= _BV (CS11);    // now prescaler of 64
    ocr /= 64;
    }

  // stop timer
  *timerRegA_ = 0;
  *timerRegB_ = 0;

  // reset counter
  *timerTCNTH_ = 0;
  *timerTCNTL_ = 0;

  // what to count up to
  *timerOCRH_ = highByte (ocr);
  *timerOCRL_ = lowByte (ocr);

  *timerRegA_ = _BV (COM1A0);             // toggle output pin
  *timerRegB_ = _BV (WGM12) | prescaler;  // CTC
  }  // end of TonePlayer::tone

void TonePlayer::noTone ()
  {
  // stop timer
  *timerRegA_ = 0;
  *timerRegB_ = 0;
  } // end of TonePlayer::noTone

/*
 PERMISSION TO DISTRIBUTE

 Permission is hereby granted, free of charge, to any person obtaining a copy of this software
 and associated documentation files (the "Software"), to deal in the Software without restriction,
 including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
 and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
 subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 LIMITATION OF LIABILITY

 The software is provided "as is", without warranty of any kind, express or implied,
 including but not limited to the warranties of merchantability, fitness for a particular
 purpose and noninfringement. In no event shall the authors or copyright holders be liable
 for any claim, damages or other liability, whether in an action of contract,
 tort or otherwise, arising from, out of or in connection with the software
 or the use or other dealings in the software.

 Example of use:

 #include <TonePlayer.h>

 ...

 TonePlayer tone1 (TCCR1A, TCCR1B, OCR1AH, OCR1AL, TCNT1H, TCNT1L);  // pin D9 (Uno), D11 (Mega)

 or, on the Mega 2560:

 TonePlayer tone3 (TCCR3A, TCCR3B, OCR3AH, OCR3AL, TCNT3H, TCNT3L);  // pin D5
 TonePlayer tone4 (TCCR4A, TCCR4B, OCR4AH, OCR4AL, TCNT4H, TCNT4L);  // pin D6
 TonePlayer tone5 (TCCR5A, TCCR5B, OCR5AH, OCR5AL, TCNT5H, TCNT5L);  // pin D46

 ...

 pinMode (9, OUTPUT);  // D9 on Uno, D11 on Mega 2560
 tone1.tone (440);     // play 440 Hz
 delay (500);          // wait half a second
 tone1.noTone ();      // stop playing

 or, on the Mega 2560:

 pinMode (46, OUTPUT);
 tone5.tone (440);

*/

Just put those two files inside a folder "TonePlayer" inside the libraries folder inside your sketches folder, and it should all work.

The library is written for the 16-bit timers, and supports Timer 1 on the Atmega328, and Timers 1, 3, 4, 5 on the Atmega2560. Comments inside the library show how to set up the other timers.


Code for Degrees not Using Audrino Nano and MKS SERVO42 42 Stepper Motor With Driver Board Closed Loop with the LCD. I have got the motor going by using the menu on board. Now able to run Code1 https://github.com/makertut/Arduino-Closed-loop.git out of GitHub and it runs as it is designed. Line 5 int numstep = 1030; cc runs the number of steps indicated and changing this number will determine the movement.
I can do the math to calculate the degrees for number of step for a particular stepper. I would like to use degrees instead of steps for my program. Does anybody know how to code this?
Thanks Greg

This is basic algebra 1.
Say steps / degree = 5
So write that as 2 fractions:
steps   5
----- = -
degree  1

Then take the reciprocal of both sides:
degrees   1
------- = -
step      5


does INPUT_PULLUP uses power? When using a digital pin as input, one has the option of using the internal arduino resistor, which is connected to VCC; that is setting the digital pin as INPUT_PULLUP, and then the pin reads HIGH. Does this uses electricity?.

I mean the resistor is connected directly to VCC and I presume electricity is constantly flowing through the system, no?.
as oppose to having the pin as just INPUT?

Only the leakage current on the input itself is constantly consumed if there is no external connection. This is usually much less than the waste caused by having the input floating.

  If a voltage between 0.8 V and 2 V is applied to the input for a prolonged period of time, this situation becomes critical and
  should not be ignored, especially with higher bit count and more dense packages [...]. For example, if an 18-bit
  transceiver has 36 I/O pins floating at the threshold, the current from VCC can be as high as 150 mA to 200 mA.


How to create delays in AVR assembly language Hi i'm new to AVR assembly language so i was trying to get delay function to create 1 ms , 100us, and 1us  delays to do that i need to figure out what to replace nop's with below here (mainboard arduino uno r3 ATmega328
Thank you.

"delay_ms%=:    nop                 ; code to replace  nop  \n"
"delay_100us%=: nop                 ; code to replace  nop  \n"
"delay_1us%=:   nop                 ; code to replace nop  \n"
"               sbiw r30,1          ; decrement ms count (r31:r30)\n"
"               brne delay_ms%=     ; loop to delay_ms while > 0  \n"
"               ret                 ; return from subroutine      \n"

The rest is below.

word millisecs;
Serial.begin(9600);
}
void setup() asm volatile(
"          ldi r16,0x3F    ; r16 = 00111111\n"
"          out 4,r16       ; set pins 8-13 as outputs in DDRB\n"
::: "r16");
millisecs = 1000;            // 1s blink delay
Serial.begin(9600);
}
void loop()
{
long starttime = millis();        // make a note of the start time

asm volatile(
// jump to "blink" - ie jump around the delay_ms subroutine
"            rjmp  blink%=        ; relative jump to 'blink' \n"
"          ldi r16,0x3F    ; r16 = 00111111\n"
"          out 4,r16       ; set pins 8-13 as outputs in DDRB\n"
::: "r16");

registers used:
r31 - millisecond count (lo byte)
r30 - millisecond count (hi byte)
r17 - 100 microsecond count
r16 - 1 microsecond count
Overall delay (ms) = r30:r31 * r17 * r16
---------------------------------------------------------------------*/
"delay_ms%=:    nop                 ; code to replace  nop  \n"
"delay_100us%=: nop                 ; code to replace  nop  \n"
"delay_1us%=:   nop                 ; code to replace nop  \n"
"               sbiw r30,1          ; decrement ms count (r31:r30)\n"
"               brne delay_ms%=     ; loop to delay_ms while > 0  \n"
"               ret                 ; return from subroutine      \n"

AVR LibC already has macros that do this, provided F_CPU is set correctly.

// Note: The Arduino IDE gets the value for F_CPU from boards.txt
#define F_CPU xxxxxxxxxx

#include <util/delay.h>

 ...

_delay_ms(1);
_delay_us(100);
_delay_us(1);


CRC test fail on MS5803-14BA pressure sensor - what can I do? Problem:

I bought two MS5803-14BA sensors and I soldered them myself to a SOIC-8 PCB to be able to use them. Only one sensor is used in my circuit. To access it, I use an Arduino Pro Mini 8MHz/3.3V with a library that has a CRC check for the sensor. When assembled to the circuit, one of the sensors pass the test, however the other fails. I'm using I2C to access the sensor.

I would like both sensors to pass the test so I could compare readings from two assembled circuits, but I really don't know how to do it. I have a three questions:

Where this problem can be originating from?
What kind of limitations I have for not passing the CRC test? Does it mean that the collected data can not be trusted?
If I use the raw readings D1 and D2 from a sensor that have failed the CRC test and pos-compensate them in the computer, will I have trustful results?
How to solve it?

Schematic:

simulate this circuit – Schematic created using CircuitLab

The resistors R1 and R2 are pull-up resistors.
The capacitor C1 is recommended by the sensor's datasheet.
Sensor's PS pin is connected to Vcc in order to select I2C mode for communication. The other option was SDI.
Sensor's CLS pin is connected to ground to select the address 0x77 to the sensor. Case it is connected to Vcc, the address is set to 0x76.

Documentation

Sensor's Data Sheet
Library used

Where this problem can be originating from?

As per page 7 and page 14 of the data sheet, there are 16 bytes of PROM in the unit which contain calibration information determined and written at the factory. This calibration information includes coefficients that must be used by whatever's reading the sensor to adjust for manufacturing variations. The data also include a CRC check code to let you confirm you've read the PROM correctly.

So there are three possibilities here:

The CRC as written to PROM is wrong.
There was an error while transferring the data from PROM to your MCU.
The software is doing the CRC calculation incorrectly.

The source code suggests that the most likely reason for this sort of failure is faulty wiring between the MCU and the sensor.

What kind of limitations I have for not passing the CRC test? Does it mean that the collected data can not be trusted?

Potentially, yes. To determine how bad things really are and what might be going wrong you need to do a bit more experimentation.

When you call the initializeMS_5803() function you pass it a boolean parameter determining whether it's running in verbose mode. Set this to true so it prints out the coefficients 0 through 7 to the serial port during initialization. Restart your Arduino several times, ideally under different conditions of temperature, power, physical wire configuration (if any), etc., and see if the values ever change. If they are ever different from a previous run, you have either cabling corrupting the data transfer or a defective sensor. You may be able to look at which bits change, if any change consistently, to get some insight into how "random" the problem really is. (Could it be that only a certain bit pattern is being transmitted unreliably?)

If all values always read the same, compare them to the values read from your good sensor. If they're quite similar, and you're generally getting similar readings under similar conditions from both sensors, I would suspect possibility 1 or 3 above, and reckon that you're likely to be getting reasonably reliable data from the sensor. If the values are vastly different this doesn't necessarily mean that the sensor will be unreliable; I have no idea how much these coefficients vary from unit to unit.

If I use the raw readings D1 and D2 from a sensor that have failed the CRC test and pos-compensate them in the computer, will I have trustful results?

Again, that depends on whether or not it looks as if you're getting corruption on the data link. As above, if you ever read different PROM data from run to run on startup, the sensor is much less likely to be producing trustworthy data.

You could also try comparing the raw readings from both sensors under conditions as close to identical as you can make them. I don't know how close in calibration the two sensors are, but if they are close, the raw data should look similar and that would be a sign of reliability.

How to solve it?

First, determine if you are getting the same or different PROM values across multiple startups. If they're always the same, send your good and bad values to the author of the driver and ask him if he thinks his CRC algorithm might have an error in it. (Or check it yourself against the application note mentioned in the data sheet, if you feel up to it.)

If the CRC algorithm in the software you're using is correct, given that you appear to reading successfully from another sensor, I'd send the sensor giving the CRC error back to the manufacturer, along with the coefficients you had read, with a query as to whether they have got the CRC wrong or you're reading the data wrong.

If you're getting different PROM values, that's either a faulty sensor or a wiring problem. You may be able to help isolate this with the usual tricks: slow down the transfer speed (with Wire.setClock()) to see if that reduces data corruption, re-wire the circuit with different (and preferably shorter) wires and other parts, make sure you've got caps in the appropriate places to filter noise, put a scope or a logic analyzer on the SCK and SDA lines to see if you can see any dodgy-looking waveforms, and so on. If anything looks strange, you can always use your working unit for comparison. If all that still looks good, it may well be a faulty sensor.


Wemos D1 mini freezing after a few minutes I´m using a Wemos D1 mini board to control a RGB LED Strip and programmed a simple code with the Arduino IDE. The Wemos conects to my Internet just fine and with the IP adress I can change the RGB values of the Strip. Everything works but after a few minutes the board freezes and nothing works. After a reset it works again.

I also conected a simple circuit to the board just to controle a RGB-LED Strip with a few transistors nothing that should cause an issue and also if i conect nothing to the board the problem occurs.

I also tested a example from the Wemos Library but there is the same problem.
Here is my code I used (And sorry if the code isn´t that well programmed I´m a beginner ;)):

#include <ESP8266WiFi.h>

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

void setup() {
  pinMode(D1, OUTPUT);
  pinMode(D2, OUTPUT);
  pinMode(D5, OUTPUT);

  WiFi.begin(ssid, pass);
  while (WiFi.status() != WL_CONNECTED) delay(500);

  Serial.begin(9600);
  //Serial.println(WiFi.localIP());
  server.begin();
}
void setColor(String rgb)
{
  String rgb_val = rgb.substring(4, rgb.lastIndexOf('H'));
  String red_val = rgb_val.substring(1,rgb_val.indexOf(':'));
  String green_val = rgb_val.substring(rgb_val.indexOf(':') + 1,rgb_val.indexOf(':',rgb_val.indexOf(':') + 1));
  String blue_val = rgb_val.substring(rgb_val.lastIndexOf(':') + 1);
  int redval = red_val.toInt();
  int greenval = green_val.toInt();
  int blueval = blue_val.toInt();
  analogWrite(D5, redval);
  analogWrite(D2, greenval);
  analogWrite(D1, blueval);

  redval = redval >= 1023 ? 1023 : redval <= 0 ? 0 : redval;
  if (redval == 0)
    analogWrite(D5, 0);

  greenval = greenval >= 1023 ? 1023 : greenval <= 0 ? 0 : greenval;
  if (greenval == 0)
    analogWrite(D1, 0);

  blueval = blueval >= 1023 ? 1023 : blueval <= 0 ? 0 : blueval;
  if (blueval == 0)
    analogWrite(D2, 0);

  return;
}

void loop() {
  //delay(50) //just a test if there are not so many updates
  WiFiClient client = server.available();
  if (!client) return;

  while (!client.available()) delay(1);

  String request = client.readStringUntil('\r');
  client.flush();

  //Serial.print(request);
  setColor(request);
  client.stop();

  client.print("HTTP/1.1 200 OK\r\n");
  client.flush();
  return;
}

Is there someone who know what I have done wrong?

I doubt this is the problem, but this code looks wrong.

  int redval = red_val.toInt();
  analogWrite(D5, redval);
  redval = redval >= 1023 ? 1023 : redval <= 0 ? 0 : redval;
  if (redval == 0)
    analogWrite(D5, 0);

I think it should be more like this:

  int redval = red_val.toInt();
  if (redval > 1023)  // If its =1023 you do need to set it to 1023.
    redval= 1023;
  else if (redval < 0)
    redval = 0;
  analogWrite(D5, redval);

The inline if statement is too ugly and doesn't really add anything.

To be honest I would look at pulling this code into functions to make it easier to read and I suspect you will find the problem.

When these microprocessors stop after a while its usually memory, heat or electrical.  If you have checked the electrics and its stopping quite quickly its probably a memory leak.  So refactoring your code might help people spot the problem easier.

You might want to replace you call to setColour()  with a call to Serial.println() and see if that cure the problem.  If it doesn't then your problem is with the way you are calling client.


Measure LiPo / Li-Ion SOC or the ever standing question of how much juice is remaining in my battery? So I have a project in which an arduino runs on a two cell LiPo battery and I need a fast, straight forward way to determine remaining battery charge (with an accuracy of 10% so I only have a readout with 10 LEDs on it) without using any major extra components (so using an external battery charge meter IC is cheating :P). How should I go about this?

(using arduino mini, LiPo is two cells: 7,4V 150mAh)

Use a low-leakage op amp to divide the battery voltage by 8 (AV of 1/8). Connect the output to an analog input. Set your reference to the internal 1.1V reference (INTERNAL). Perform analog reads. Full battery will be about 975 ((8.4V/8)/1.1V⋅1024 ~= 977.45455). Empty will be about 700 ((6.0V/8)/1.1V⋅1024 ~= 698.18182). Note that the voltage scaling for Li-ion cells is non-linear; see the datasheet for the cells for the appropriate scaling (and if you want more precise full and empty values).


ATtiny85 AC Phase Control for dimming a light bulb I'm trying to dim a light bulb via an ATtiny85, which accepts commands sent over I2C. My problem is that the bulb is barely dimming and is flickering quite a bit.

My circuit can be seen here:

The opto-isolator (and thus the triac) is controlled via pin 2 (AKA PB3, AKA PCINT3) and AC zero cross detection is done on pin 3 (AKA PB4, AKA PCINT4) on the ATtiny85.

The code uses Pin Change Interrupt Enable rather than the single External Interrupt Enable, because the External Interrupt pin is pin 7 (aka PB2), which is used as the SCL for the I2C communication.

The 8MHz internal clock is used and the timer/counter prescaler is 1024, which means that I have an effective input range (see level variable in the code) of roughly 0-65. My AC source is USA (60Hz).

#include <avr/interrupt.h>
#include <avr/io.h>
#include <TinyWireS.h>

#define PULSE 4       //trigger pulse width (counts)
#define I2C_SLAVE_ADDR 0x4 // the 7-bit address (remember to change this when adapting this example)

byte trigger = 3;
byte detector = 4;
byte level = 50;
byte maxLevel = 65;
byte minLevel = 0;

void setup() {
    TinyWireS.begin(I2C_SLAVE_ADDR); // join i2c network
    TinyWireS.onRequest(requestEvent); //setup i2c requester
    digitalWrite(detector, HIGH);  //enable pull-up resistor
    pinMode(trigger, OUTPUT);// Set AC Load pin as output
    TCCR1 = 0;     //stop timer
    OCR1A = level;    //initialize the comparator
    TIMSK = _BV(OCIE1A) | _BV(TOIE1); //interrupt on Compare Match A and  enable timer overflow interrupt
    GIMSK = 0b00100000; //Enable pin change interrupt
    PCMSK = 0b00010000; //PB4, physical pin 3 PCINT4
    TCCR1 = B00001011; //Prescale the timer
    sei();  // Turn on interrupts
}

ISR(PCINT0_vect) {
    //interrupt looking for zero crossing
    TCNT1 = 0;   //reset timer - count from zero
    OCR1A = level;
    TCCR1 = B00001011;// prescaler on 1024, see table 12-5 of the tiny85 datasheet
}
ISR(TIMER1_COMPA_vect) {
    //comparator match
    digitalWrite(trigger,HIGH); //set triac gate to high
    TCNT1 = 255-PULSE;
    //trigger pulse width for a few cycles for triac to latch on. 255 bc the counter can only count up to 255
}

ISR(TIMER1_OVF_vect) {
    //timer1 overflow
    digitalWrite(trigger, LOW); //turn off triac gate
    TCCR1 = 0;  //disable timer stop unintended triggers
}

void loop() {}

void requestEvent() {
    if (TinyWireS.available()) {
        level = TinyWireS.receive();
        if (level > maxLevel) {
            level = maxLevel;
         else if (level < minLevel){
            level = minLevel;
        }
    }
    TinyWireS.send(OCR1A);
}

I have tried a variety of bulbs (incandescent and dimmable LED), with none working any better than another.

Here is a video showing the zero cross detection (yellow) and the ATtiny85 trigger (blue) on an oscilloscope as I send it different dimming levels Bad phone video

I've thought about the snubber, I just don't have the parts on hand right now. I think it will help but I don't think it will correct whatever my larger issue is.

I'd appreciate all and any help. Thanks.

(Note: I also posted this here. Apologies if crossposting is frowned upon).

So I think there were (was?) two issues.

1) Pin change interrupts on the Attiny85 are triggered on rising and falling edges which I think was causing the flickering.

I changed the code to rising edge only triggering:

ISR(PCINT0_vect){ //interrupt looking for zero crossing
        if (digitalRead(4) == HIGH){
                TCNT1 = 0;   //reset timer - count from zero
                OCR1A = level;
                TCCR1 = B00001011;// prescaler on 1024, see table 12-5 of the tiny85 datasheet
       }
}

2) Attiny85 #reset pin. Pulled that guy high with a resistor.

Anyways, here's the oscilloscope and dimming led blub video: youtube


How can I connect an OLED display to arduino I'm new on this!

So I want to know if is it posible to connect this oled display: oled display to arduino nano and if is it posible where can I found information of how to learn about connect this type of mini display.

And if you can share some links about good learning site would be cool too!

Thanks!

Yes, you can. If you have the adaptor board for it as shown in the video.

The key item from the description to note is the driver chip: SSD1309

That is what you need to know to find a library and connection schema.


Arduino MPU6050 Control 2 Servo I'm new to gyroscope and accelerometer and am working on my project to control servo with Arduino Uno R3 based on the reading from InvenSense MPU6050 6DOF gyroscope and accelerometer. I've found the a same sheet of code from different websites.

Website 1_http://www.projehocam.com/wp-content/uploads/mpu6050-2-servo.txt

Website 2_http://www.instructables.com/files/orig/FLY/GZAL/IDIN48PC/FLYGZALIDIN48PC.ino

And from this part of the code, I couldn't understand the servo.write part...

    #ifdef OUTPUT_READABLE_YAWPITCHROLL
        // display Euler angles in degrees
        mpu.dmpGetQuaternion(&q, fifoBuffer);
        mpu.dmpGetGravity(&gravity, &q);
        mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
        Serial.print("ypr\t");
        Serial.print(ypr[0] * 180/M_PI);
        Serial.print("\t");
        Serial.print(ypr[1] * 180/M_PI);
        myservoY.write(int(ypr[1] * -180/M_PI)+90);   // Rotation around Y
        Serial.print("\t");
        Serial.println(ypr[2] * 180/M_PI);
        myservoX.write(int(ypr[2] * 180/M_PI)+90);   // Rotation around X
    #endif

Why is the operation (int(ypr[1] * -180/M_PI)+90) ??

ypr contains the Yaw, Pitch and Roll. It is provided in radians.

Servo.write takes degrees.

Multiplying radians by 180/PI converts it to degrees.  Adding 90 centralises it around the 90 degree point (half way) of the servo.


use shiftIn and shiftOut with attiny85 I want my Attiny85 to communicate with another attiny85.
one attiny should send a message to my other attiny. When he receives the correct message he should turn one led on. Just a very simple test scatch.
I don't know why but the led never turns on.

Here is my code:

1st attiny85:

int clk_pin = 4,
    data_pin = 3,
    led = 0;

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

void loop() {
  byte incoming = shiftIn(data_pin, clk_pin, LSBFIRST);

  if (incoming == 2)
  {
    digitalWrite(led, HIGH);
    delay(1000);
    digitalWrite(led, LOW);
    delay(1000);
  }
}

2nd attiny:

int clk_pin = 0,
    data_pin = 1;

void setup(){
  pinMode(clk_pin, OUTPUT);
  pinMode(data_pin, OUTPUT);
}

void loop(){
  byte test = 2;
  shiftOut(data_pin, clk_pin, LSBFIRST, test);

  delay(5000);
}

I think there might be something wrong with my shiftIn/shiftOut command. It's actually the first time I'm using this.

Thanks for helping!

shiftIn() and shiftOut() are designed for communicating with different types of shift registers. These are typically external components which don't run code themselves, such as the 74HC595.

You can't use shiftIn() to read data that's been written using shiftOut(). The reason is that both functions try to act as the host in the communication -- i.e. the one that controls the clock line.

When you call shiftIn(), the clock line is pulsed each time it's ready to read a bit (i.e. it tells the shift register when to write). When you call shiftOut(), the clock line is pulsed each time it writes a bit (i.e. it tells the shift register when to read).

Neither one will respond to a clock line provided externally. The result is that your ATTiny's aren't synchronised so they won't be reading/writing at the same time.

A much simpler approach would be to setup a conventional serial connection between the two microcontrollers. You could do that either using software or hardware serial. The only caveat is that the sender would need to ensure the receiver is up-and-running before it transmits anything. This could be done using some kind of handshake at startup -- one device repeatedly sends something until the other replies.


Serial.write without a receiver I'd like to send  a monitoring information (temperature) to a serial receiver periodically. The problem is I don't know if there is any monitoring service (serial receiver) and how fast it is reading. I only need the latest value. The problem is that serial.write will block if the buffer is full. If I skip writing if the buffer is full, a receiver will only get old data on the first connect. How can I replace data in the buffer or make sure there is only one dataset in the buffer?

The problem is that serial.write will block if the buffer is full.

Only until the bytes get sent out through the TX pin.

  If I skip writing if the buffer is full, a receiver will only get old data on the first connect.

No it won't. There is no "old" data.

  How can I replace data in the buffer or make sure there is only one dataset in the buffer?

You don't need to.

You are showing a fundamental misunderstanding of how serial works.  When you send data it just twiddles the TX pin in the right way with the right timing. If there is something connected to it that understands that twiddling at the speed it's being twiddled then it interprets it as serial data. If there's nothing to see that twiddling it still twiddles.  The "blocking" is only if you try and send more data than the serial port can physically send out in the time you're sending it.

If a serial port transmits in a forest and there is no one there to hear it, yes, it still makes a noise.


Field Programming a Arduino with another Arduino with SD card over RX/TX lines I am not sure if this question has been asked before but here's what I wanted to do.

I have a Arduino Nano, which I need to update with a new sketch. The plan is to be able to use another Arduino (maybe a Nano again), with an SD card reader and a sketch loaded as HEX file on it. Then connect both using a 4 pin RX/TX/5V/GND and upload the sketch from the transmitter to the receiver. Is it possible?

I am not sure how to do this; I know I can use one Arduino as an ISP to update other, but I am thinking of streaming the hex file to the other. Has anyone done this, any hints would be extremely helpful.

There's actually a library for that as well! See here and here.


Resetting Arduino UNO code (newbie) So today I started to learn Arduino uno. I have an LM35 temperature sensor and I got what I needed from it. Now it's just keep calculating till I plug it off.

I know there is a reset button. When I press it or hold it, it's closing and opening again to do the coding again. I want it to completely stop. Like when I first plug led was flashing to show arduino is connected.

And I know I can just upload another code. But I don't want that.

If it's possible please let me know.

When a microcontroller or a computer is powered on, it always does something. A program on a computer will return and the OS will run again. On a microcontroller there is no OS to return to, so every microcontroller program has an infinite loop.

The void loop() function of the Arduino framework is such an infinite loop. If you want your LM35 temperature code to be only run once, you can put it into the void setup() function, which is run once before going to loop(). When the loop() function is empty, the Arduino will do nothing after it returned from setup().

Otherwise, if you want to put your code into loop() for whatever reason, you can insert an infinite loop whereever you want it:

while(true);

This loops forever and does nothing. Your temperature code will only be executed on the next reset or power on.