Serial communication between Arduinos I'm trying to send data from Arduino Mega to UNO.
The master code sends characters 'x' and 'a' every half second to the slave Arduino UNO.
Slave receives the characters and switches the state of the onboard LED.
Here I'm trying to print some text in the beginning of the loop and the characters received.
Instead of the letters it is printing numbers as given below.
Why this line Serial.println('Soft serial avaialble') prints numbers?
How to print real text received from the master?
> 27749
> 97
> 27749
> 120
> 27749

Master code:
// Include the Software Serial library
#include <SoftwareSerial.h>
// Define a Software Serial object and the used pins
SoftwareSerial softSerial(8, 9);  // RX, TX
void setup()  {
    Serial.begin(9600);
    softSerial.begin(9600);
}
void loop()  {
    // Sends characters 'x' and 'a' every half second.
    if (Serial.available())  {
        softSerial.write('x');
        delay(500);
        digitalWrite(LED, LOW);
        delay(500);
    }
}

Slave code:
// Include the Software Serial library
#include <SoftwareSerial.h>
// Define a Software Serial object and the used pins
SoftwareSerial softSerial(8, 9);
// LED Pin
int LED = 13;

void setup()  {
    softSerial.begin(9600);
    Serial.begin(9600);
    pinMode(LED, OUTPUT);

}
void loop()  {
    Serial.println('Soft serial avaialble');
    if (softSerial.available())  {
        int com = softSerial.read();
        if (com == 'x')  {
            Serial.println(com);
            digitalWrite(LED, LOW);
        } else if (com == 'a'){
            Serial.println(com);
            digitalWrite(LED, HIGH);
        }
    }
}

In your slave, you've declared com as an int, so Serial.println() interprets it that way. If you want to keep it as int except for printing, cast Serial.println()'s argument to char:
Serial.println((char)com);


GSM and GPS module don't work together I am trying to create a project which involves getting latitude and longitude via GPS Module and send it via GSM Module. My problem here is that individual code is working perfectly. However, if am to initialize both together, none will work.

#include "GSM.h"//wrapper class for Sim800l library
#include "GPS.h"//wrapper class for TinyGPS library
GSM *gsm;
GPS *gps;
void setup()
{
    Serial.begin(9600); // Debugging only
    gsm = new GSM();//initializes SIM800l
    //gps = new GPS(11,10 );//initializes NEO6MV2//uncommmenting this line won't make both modules work
}
String telNum;
int i = 1;
void loop()
{
    /*
    Serial.println(gps->getLongitude(),6);
    Serial.println(gps->getLatitude(),6);
    */

    Serial.println(gsm->read(i,telNum));
    Serial.println(telNum);
     ++i;
}

You can't use two softwareserial devices together (or not reliably, and not without knowing exactly what you are doing).

It's not even easy using one software and one hardware serial together unless you know what you are doing.

SoftwareSerial blocks everything else from happening while it's sending or receiving, so using it for things that send unsolicited messages (as GPSs do all the time) causes havoc.

The best you can hope for is to use HardwareSerial for the GPS and SoftwareSerial for the GSM, which is call-and-response most of the time.

Better would be to use a better board that has multiple hardware serial ports.


Perfect copy of Yun with Micro SD My Yun has a micro SD card with shared file system using ExpandingYunDiskSpace.

I would like to copy my Yun/SD card data perfectly onto my backup Yun/SD card. Because I have made many changes to the filesystem, just re-running the whole process manually would take a long time.

What methods can I use to transfer my Yun's data onto my other Yun?

My other Yun is brand new (never plugged in), and I have a brand new SD card in there. If I can do a 'bit-perfect' transfer for Yun and Micro SD in one shot that would be ideal.

Copying an SD card (cloning) is easy enough to do.  On Windows you can use Win32DiskImager.  On Linux and OS X you can either use dd from the command line:

(read)
$ dd if=/dev/sdb of=MySD.img bs=32k

(write)
$ dd id=MySD.img of=/dev/sdb bs=32k

For OS X the device names will be different, also in Linux you need to check which /dev/sd?? it is.

Also in Linux and OS X there are GUI applications that can do it for you - the Disk Manager in OS X, and "Gnome Disks" in Linux.

That is only good for the actual SD card contents though.  If you need to clone the actual Yún itself then it becomes more tricky.

Fortunately there are tools available to help you.

Details on how to create and restore a backup of an OpenWRT system (which is what the Yún is) can be found on the OpenWRT Wiki: http://wiki.openwrt.org/doc/howto/generic.backup

Note that again it requires a Linux or OS X (preferably the former) system to do it since it relies on the standard Unix scripting tools and commands that are lacking on a Windows system.

You may be able to do all the above on a Windows system if you make it look like a Linux system by installing Cygwin.


FC-16 led matrix module based on MAX7219 EDIT:

const char  *pc[NUM_ZONES] =
{
  "ROOM", //0
  "SUBJECT", //1
  "GRADE",//2
  };

I did this and I can't get them to display every row simultaneously.

void loop(void)
{

 DateTime now = rtc.now();
 char buffer[] = "hh:mm";  // hours and minutes

 for (uint8_t i=0; i<NUM_ZONES; i++){
   P.displayZoneText(0,now.toString(buffer), PA_CENTER, 0, 0, PA_PRINT, PA_NO_EFFECT);
   P.displayZoneText(1, pc[1], PA_CENTER, 0, 0, PA_PRINT, PA_NO_EFFECT);
   P.displayZoneText(2, pc[2], PA_CENTER, 0, 0, PA_PRINT, PA_NO_EFFECT);  // display
   P.displayZoneText(3, pc[3], PA_CENTER, 0, 0, PA_PRINT, PA_NO_EFFECT);
 }
}

I can only display one row at a time like this, now it only displays the hour:min.

Tell me what am I doing wrong

EDIT2:

Or like this:

-this is my goal, to change the text based on hour

void loop(void)
{

 DateTime now = rtc.now();
 char buffer[] = "hh:mm";  // hours and minutes

   P.displayZoneText(0,now.toString(buffer), PA_CENTER, 0, 0, PA_PRINT, PA_NO_EFFECT);

   if(now.hour()==21){
   P.displayZoneText(1, pc[1], PA_CENTER, 0, 0, PA_PRINT, PA_NO_EFFECT);
   P.displayZoneText(2, pc[2], PA_CENTER, 0, 0, PA_PRINT, PA_NO_EFFECT);  // display
   P.displayZoneText(3, pc[3], PA_CENTER, 0, 0, PA_PRINT, PA_NO_EFFECT);
   }
   P.displayAnimate();
}

And at the moment with this code it only displays the hour and minutes

I haven't used this library, but reading through the documentation it seems it operates on the concept of zones.

Create a zone for each row (a zone is a contiguous block of modules forming a kind of sub-display)
Perform operations on the zones with the zone-specific functions.

For example, setting up your zones would be:

P.begin(4); // We will have 4 zones
P.setZone(0, 0, 3); // Modules 0-3 in zone 0
P.setZone(1, 4, 7); // Modules 4-7 in zone 1
P.setZone(2, 8, 11); // Modules 8-11 in zone 2
P.setZone(3, 12, 15); // Modules 12-15 in zone 3

Then you can clear a zone with:

P.displayClear(2); // Clear zone 2

And write text to a zone with:

P.displayZoneText(3, "P03", PA_CENTER, 0, 0, PA_NO_EFFECT, PA_NO_EFFECT);

I'm not certain about what all the parameters mean, but the prototype is:

void displayZoneText(uint8_t z, const char *pText, textPosition_t align, uint16_t speed, uint16_t pause, textEffect_t effectIn, textEffect_t effectOut = PA_NO_EFFECT);


Is there a Arduino UI library that provides dialog box and button functionality at a minimum? I have been looking at the Arduino TFT Library and it supports all the bits and pieces for making a simple display, but I am looking for something a little higher level that has primitive dialog box and button capability, and presumably, the ability to layer the display so I can push and pop display elements.  Is there a higher level GUI library for Arduino TFT displays?

Take a look at this library. Will this do all that you want?
https://github.com/AndreiDegtiarev/AWind
I have not tried it yet but I would like to.
Edit:
I just remembered this https://github.com/ImpulseAdventure/GUIslice
https://github.com/ImpulseAdventure/GUIslice/wiki
A lightweight GUI framework for embedded displays
The library supports creation of multiple pages of buttons, text, images, checkboxes, sliders and other graphics primitives. New UI / widget types can be created easily.
It works with many existing TFT libraries. There also is a drag & drop builder application.  https://github.com/ImpulseAdventure/GUIslice-Builder


Changing Arduino Outputs into Binary I am new to Arduino so please give me some advice on this really simple problem. I am currently using an Arduino Mega in a school project to make 4 capacitive sensors which are supposed to receive an input when you touch the sensors, and I have programmed the arduino such that you will light up an LED upon touching the sensors.

Now the problem is after I light up the LEDs the serial data monitor gives me many different numbers when I am touching the sensors. Is it actually possible for me to tweak my program such that outputs of my sensor will show up as a single line of '0' when the sensor is not being touched and '1' when the sensor is being touched? This would really help me in the quantifying of some of the data I would wish to collect from my experiments with the sensors.

My code is

#include <CapacitiveSensor.h>

CapacitiveSensor   cs_2_4 = CapacitiveSensor(2,4); // 1M resistor between pins 4 & 8, pin 8 is sensor pin, add a wire and or foil
CapacitiveSensor   cs_5_7 = CapacitiveSensor(5,7);
CapacitiveSensor   cs_8_10 = CapacitiveSensor(8,10);
CapacitiveSensor   cs_11_13 = CapacitiveSensor(11,13);

void setup()
{
   cs_2_4.set_CS_AutocaL_Millis(0xFFFFFFFF);// turn off autocalibrate on channel 1
   cs_5_7.set_CS_AutocaL_Millis(0xFFFFFFFF);
   cs_8_10.set_CS_AutocaL_Millis(0xFFFFFFFF);
   cs_11_13.set_CS_AutocaL_Millis(0xFFFFFFFF);

   Serial.begin(9600);
   pinMode(3,OUTPUT);
   pinMode(6,OUTPUT);
   pinMode(9,OUTPUT);
   pinMode(12,OUTPUT);
}

void loop()
{
 long sensor1 =  cs_2_4.capacitiveSensor(50);
 long sensor2 =  cs_5_7.capacitiveSensor(50);
 long sensor3 =  cs_8_10.capacitiveSensor(50);
 long sensor4 =  cs_11_13.capacitiveSensor(50);
Serial.print("\t");
Serial.println(sensor1, BIN);  // print sensor output
Serial.print("\t");
Serial.print(sensor2, BIN);
Serial.print("\t");
Serial.print(sensor3, BIN);
Serial.print("\t");
Serial.print(sensor4, BIN);

    if(sensor1 >= 1000)
   {
    digitalWrite(3,HIGH);
   }
   else{
    digitalWrite(3,LOW);
   }
     if(sensor2 >= 1000)
   {
    digitalWrite(6,HIGH);
   }
   else{
    digitalWrite(6,LOW);
   }
    if(sensor3 >= 1000)
   {
    digitalWrite(9,HIGH);
   }
   else{
    digitalWrite(9,LOW);
   }
    if(sensor4 >= 1000)
   {
    digitalWrite(12,HIGH);
   }
   else{
    digitalWrite(12,LOW);
   }
   }

and the output that I end up receiving is

Hence it would be really great if I could tweak my code such that the output on the serial monitor would be '0' when there is no output(Not touching sensor) and '1' when there is an output (touching sensor)

Thanks a lot for the help once again!

It sounds like what you want isn't really "binary", nor the bit-to-characters expansion of the touch readings.

Rather it sounds like what you want to do is to print the character '0' or '1' for the state of each button.  You already have the decisioning code for your outputs, so you can simply extend it for the serial prints:

if(sensor1 >= 1000) {
   digitalWrite(3,HIGH);
   Serial.print("1");
} else{
   digitalWrite(3,LOW);
   Serial.print("0");
}

and so on, with the next set having tabs and the last a newline.

Worth noting, intermixing the printing and digital outputs will put some time delay between the outputs (potentially quite a bit if the evaluation gets ahead of the serial buffers), so another option could to do all the outputs and then all the prints, or store the decisions in a bit mask for later printins, etc.


Need little bit of help on testing I2C sketch I have this code I got from YouTube for communicating between two Arduinos. By typing 'R' manually into the serial monitor of the 'master' Arduino, the 'slave' will print "Success". I'm trying all this for the basis of a project I'm starting.

After success with the code, I am now trying to make it automatic. I want the 'master' Arduino to print "R" itself and for the 'slave' to read this and print "Success". println doesn't work here, maybe it'll work if the slave code is changed? Both original codes are below, any ideas on how to do what I need?

Master:

#include <Wire.h>
char incomingByte;
int x = 0;

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

void loop()
{
  Wire.beginTransmission(9);
  if (Serial.available()) {
    while (Serial.available() > 0) {
      incomingByte = Serial.read();
      Wire.write(incomingByte);
      Serial.println(incomingByte);
      Wire.endTransmission();
  }
  }

}

Slave:

#include <Wire.h>

int x = 0;

void setup() {
  Wire.begin(9);
  Wire.onReceive(recieveEvent);
  Serial.begin(9600);
}

void recieveEvent(int bytes) {
  x = Wire.read();

}

void loop() {

  if (x == 'R'){
    Serial.println("Success");
    delay(100);
  }
}

The I2C communication is not easy and there are many things that can go wrong. Two Arduino boards instead of one board are often used for the wrong reason in the first place.

Using a serial port is easier. The Arduino Leonardo has an extra hardware serial port, you could use the serial port to communicate between two Arduino boards. The Arduino Mega 2560 has three extra serial ports.

Sometimes two Arduino boards are used because multiple things have to be done at the same time.
When you use the Blink Without Delay example with millis, then the Arduino can do many things at the same time.

Sometimes two Arduino boards are used because there is some distance between the Arduino boards.
The I2C bus is a "bus", but that does not mean that you can use a long cable. You can go up to 20 inch (50 cm).

When two Arduino Uno boards are connected with the I2C bus, then three wires are needed:

GND to GND
SDA to SDA  (plus pullup resistor)
SCL to SCL  (plus pullup resistor)

For a small test with short jumper wires, it is possible to do that without pullup resistors. For the final project pullup resistors should be used for SDA and SCL, for example 4k7 or 10k.

The example below uses a flag in the Slave Arduino. That extra variable makes it easier.
In the Slave receiveEvent function, there is a extra check to check if exactly one byte is received. That extra check is not required, but it can be useful.

I show this example as something to start with, because there are too many bad examples for I2C between Master and Slave.

Master

#include <Wire.h>

byte dataTransmit;

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

void loop() {
  Wire.beginTransmission(9);   // sending to slave with i2c address 9
  Wire.write(dataTransmit);    // the data to send
  Wire.endTransmission();

  dataTransmit++;              // all numbers from 0 to 255

  delay(250);                  // 250ms delay, to send 4 times per second
}

Slave

#include <Wire.h>

volatile byte dataReceive;
volatile bool newData;    // a flag to indicate that new data has arrived

void setup() {
  Wire.begin(9);          // create i2c slave at i2c address 9
  Wire.onReceive(receiveEvent);
  Serial.begin(9600);
}

void loop() {
  if(newData) {           // is there new data?
    Serial.print("Received: ");
    Serial.println(int(dataReceive)); // convert to integer to print the number
    newData = false;      // reset flag
  }
}

void receiveEvent(int howMany) {
  if(howMany == 1) {      // extra check, to check if one byte is received
    dataReceive = Wire.read();
    newData = true;       // set flag, there is new data
  }
}


Very Basic Arduino Uno Serial.readString() operation I am very new to Arduino Programming.
I am trying to identify the input string from serial monitor and printing the output to the console accordingly

Code is :

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

void loop() {

   while (Serial.available() > 0 ) {

     String str = Serial.readString();

     if (str.equals("send")) {
        Serial.println("identified");
     } else {
        Serial.println("unknown");
     }

   }

}

Whenever i put send string it is showing "unknown" as the output, which is wrong, and i should get "identified" as the output.
Can anyone guide me here to achieve the result.

Note : I am getting output as i wanted by using readStringUntil function but the strings has a lot of "." in it, hence not useful.

If you set your Serial Monitor's line ending to "Both NL & CR", then this code will find the word "send". It will NOT find the word "send" in this string, "ssend" or in this string, "sendd".

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

void loop(){
  while(Serial.available() > 0 ){
    String str = Serial.readString();
    if(str.substring(0) == "send\r\n"){
      Serial.println("identified");}
    else{
      Serial.println("unknown");
    }
  }
}

If you want to find the string "send" in "1234send" or "send1234" or "1234send5678" then use indexOf();

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

void loop(){
  while(Serial.available() > 0 ){
    String str = Serial.readString();
    if(str.indexOf("send") > -1){
      Serial.println("identified");}
    else{
      Serial.println("unknown");
    }
  }
}


How to install several IDE version on my PC How can i install old version of IDE, without uninstalling the other version?(How can i install several IDE version in same laptop).

Arduino.cc have a guide :

https://www.arduino.cc/en/Guide/PortableIDE

The gist is:

Download the desired version in ZIP format
Unpack the content in the zip file to a folder
Start the arduino.exe in that folder.

Remember that you have to place all libraries, board definitions in that folder.

The folder can be copied to another computer or a USB stick....


Using logical operators This is a snip it of code from a program I am writing. I have the program turn an LED on and if a button is pressed when the LED is on I want it to add to a counter and print the counter value. The problem seems that my if statement is skipped. Right now the while loop is setup for 5 seconds using millis() and stays off using a short delay. This part (button_press_9())) is a function call to a Boolean I have setup for debouncing. If I put the function call in an if statement by its self for example to test it. It works and will turn an LED on and off. It seems the combination of the two is incompatible.

Thank you in advance.

unsigned long previousMillis = millis();
unsigned long currentMillis = millis();

while ((currentMillis - previousMillis) < onTime)
{
    digitalWrite(ledPin4, HIGH);
    if (ledPin4 == HIGH && (button_press_9()))
    {
        counter++;
        Serial.println(counter);
        currentMillis = onTime * 100;
    }
    currentMillis = millis();
}
digitalWrite(ledPin4, LOW);
delay(1000);

You should use

if (digitalRead(ledPin4) == HIGH && (button_press_9()))

instead of

if (ledPin4 == HIGH && (button_press_9()))


Consulting and inserting a string into an array if it doesn't exist (Arduino IDE) 1 Sorry that I repeat my question, I can't enter to my user...

In the project I'm doing, I connect an arduino mega with ethernet and Post some Strings to the server. The arduino mega has a receiver(315MHz). I have some arduinos nano connected with PIR sensors that sends a some int with transmitters (315MHz). What I want to do is a list in my arduino mega that stores the values sent by the arduinos nanos to use them to my server (using POST). my question is the following:

If I had an empty array, what I would like to do is

listOfSensors[]={}

void funtion (String sensor){
    if (sensor is inside listOfSensors){
         //dont do anything
    }
    else {
         add sensor to listOfSensors
    }

I have been looking for hours, but I haven't found anything so far... Anyone has any idea? Thanks!!

In C there is no such thing as an "empty array".  All arrays have a finite pre-defined size.

String sensors[10]; // Room for up to 10 sensors

The usual way of storing an unknown number of entries that will be added to "as and when" is to use a linked list or doubly-linked list.

A linked list is a list of items where each item also contains a pointer to say where the next item in the list is located.

Also you shouldn't use the String class as it is not good when working with linked lists (or in general - stick to C strings).

Warning: linked lists aren't for the faint of heart.

First you would define a struct to store the data you want in the linked list:

struct sensor {
    char *name;
    int currentValue;
    struct sensor *next;
};

That would store the name of the sensor ("name"), the current value from the sensor ("currentValue") and also contains a pointer ("*next") to the next entry in the list.  That last bit is the most important.

Now you create a "head" pointer variable to start your list off:

struct sensor *mySensors = NULL;

That starts out as NULL to say "This variable has nothing in it at the moment".

Now that was the easy part.  The hard part is adding entries to the list...

A couple of helper functions can be of use here.  Let's start by defining a function that will look for a specific entry by name in the list:

struct sensor *findSensor(const char *name) {
    for (struct sensor *scan = mySensors; *scan; scan = scan->next) {
        if (strcmp(scan->name , name) == 0) {
            return scan;
        }
    }
    return NULL;
}

That will start off with a pointer variable scan pointing to the first entry in the linked list (mySensors).  While it's pointing to a valid entry (not NULL) compare the name to the given string and if they match then return the entry we are pointing to.  Next point to whatever the "next" pointer is pointing to, so you move down the list.

Now to add a sensor:

struct sensor *addSensor(const char *name, int value) {
    // First look to see if it exists:
    struct sensor existing = findSensor(name);
    if (existing != NULL) { // We found it
        existing->currentValue = value; // Update the value
        return existing;
    }
    // We haven't got it in our list, so create a new entry:
    struct sensor newsensor = (struct sensor *)malloc(sizeof(struct sensor));
    // And fill in the data:
    newsensor->name = strdup(name); // Create a COPY of the string
    newsensor->currentValue = value; // Store the value
    newsensor->next = NULL;
    // IMPORTANT: The new entry must point to NULL to mark the end of the list:
    newsensor->next = NULL;

    // Now where to add it in the list? Is there even a list?
    if (mySensors == NULL) {
        // No? Then we just make our new entry the head of the list:
        mySensors = newsensor;
        return newsensor;
    }
    // Otherwise we need to scan through the whole list to find
    // where the tail of the list is:

    struct sensor *scan = mySensors;
    // While the current entry points to a valid next entry
    while (scan->next) {
        // move on to that next entry
        scan = scan->next;
    }
    // There must be no valid next entry now (scan->next == NULL), so
    //  add our new sensor as the next valid entry:
    scan->next = newsensor;
    return newsensor;
}

Removing a sensor from the list is a much more involved process (even more than adding a sensor).  You need to "splice" the list around the deleted entry.  I'll add detail on that if you need it, but by the sound of things you won't be removing entries, only adding them.

The routines shown there (I haven't actually tested them, but it is standard code I write all the time) aren't as efficient as they could be.  If you are adding and removing entries all the time and you end up with quite a large list it can take longer and longer to scan right through the list to find the last entry to add to.  If that is the case you can maintain a "tail" pointer that you always update to point to the last added entry whenever you add one.  That can then be used to rapidly add to the end of the list without having to scan through the whole list every time.

Another optimisation if you do a lot of scanning around within a list is to make a doubly linked list.  This is just like the linked list above except it works in both directions.  Not only do you store a next pointer, you also store a previous pointer.  You can now scan in either direction - from head to tail or from tail to head, or hopping around at will inside the list.  That is especially useful if you want to do things like ordering the list alphabetically.


use only one input pin in L293? I have an L293 motor driver chip, in which the two input pins are used in order to turn the motor forward or reverse, or stop it. So I wοnder if I could use only one input pin, ...

For running mode: Since Input1 should be the opposite of Input2, why not sending a signal from Input1 to Input2 via a hex inverter?

For stop mode: why not just sending analogWtite(Enable, 0) to Enable pin?

That way I could save an extra Output pin from Arduino. Do I lack some important detail?

My question goes the same for all the L29x family.

A H-Bridge has 3 modes of operation in addition to disabled. The ENable pin, when driven low, disconnects the power and stops the motor from being actively driven it is true. However that is not the same as the STOP mode of the H-Bridge.

The logical internal connections in the H-Bridge for the three modes are like this:

When in STOP mode the motor is effectively short circuited and the power supply is disconnected. When the motor is spinning and not being actively driven it is generating power. By feeding that power into a load you increase the load on the motor itself, slowing it down. The bigger the electrical load the slower the motor will go - and you can't get bigger than a dead short. So this mode effectively stops the motor in its tracks. It puts the breaks on.

Conversely, if you just disconnect the power, there is nothing much to stop the motor spinning, so it will keep going depending on the amount of friction, wind resistance, inertia, momentum, etc.

If you are happy with that kind of operation then yes, your method will work fine, since you will have access to forward, reverse, and a way of controlling the power to the motor. You just won't be able to apply the brakes, and you will have to either rely on the natural slow-down of whatever you are driving, or do something clever involving using just enough reverse to stop the motor before cutting the power.


Send signal to vibrate a Restaurant buzzer via web based app to a PC I'm new to Arduino, I want to create a restaurant buzzer using Arduino and it should turn on/off via web based interface. It will be locally connected only.

Is it possible to send a signal with the mac address of the master transmitter pc to vibrate the buzzer?

What are the materials should I need? Suggestions or any tips is greatly appreciated.

You need a webserver, a defined interface for the client to connect to and a buzzer you can make some noise with.

Because you want to do it over WIFI, an Arduino is probably not the best choice.  As 'Look Alterno' says you might be better with an ESP8266 based device, because that has inbuilt WIFI.  I would suggest a Wemos D1, its an ESP8266 12 with a power supply and 2.54 pitch connectors, which means its easy to use with things.

Now you can program an ESP8266 using LUA, but I really wouldn't try that. Also if you do that you won't get any help on this forum.  Use the Arduino IDE and program it in the same language as an Arduino (You will need to download support for the ESP via the Board Manager in the IDE).  There is an example called "Advanced Web Server", done by Majenko on here, that will suit your needs.  You just need to change the root handler to activate the buzzer for n seconds and then return HTTP code 200.

Then your client just needs to connect to the root page of the webserver and the buzzer will sound.  You don't say how many clients will use this, but this will allow 5 simultaneous clients, if you need more that can be achieved easily.

You can then expand this to identify which client sounded the buzzer.

As to keeping it local, use the firewall on your router.


declared variable inside void setup is forgotten in void loop if i declare a var in void setup() and try to do something with it in void loop(), it just says that the variable is undeclared. here is the code:

#include "Servo.h"

void setup() {
    Servo servo1;
    int x_key = A0;
    servo1.attach(2);
    pinMode(A0, INPUT);
    pinMode(2, OUTPUT);

    int x_position = 90;
}

void loop() {
    if (analogRead(A0) < 512) {
        x_position++;
        servo1.write(x_position);
    }
}

Yes, that is how C and C++ (and most other C-like languages) work. Variables have "scope". Any variable define inside a pair of curly braces (between a { and a }) is only visible inside those braces.

If you want to reference a variable in both setup() and loop(), you have to make it a global variable, defined at the top of your code.

#include "Servo.h"
Servo servo1;
int x_position = 90;  //Define your global var(s) here

void setup() {
    int x_key = A0;  //This var only exists inside the setup function
    servo1.attach(2);
    pinMode(A0, INPUT);
    pinMode(2, OUTPUT);

}

void loop() {
    if (analogRead(A0) < 512) {
        x_position++;
        servo1.write(x_position);
    }
}


How to control a large number of devices with an Arduino I'm doing some initial research on a project I have in mind. I am super new to all this Arduino stuff so taking it slow and gathering lots of info.

I want to control around 1000 small linear actuators to push/pull a very small load. The purpose of this question is specifically how to manage that many devices. The devices won't ever need to start their own transmissions so the Arduino can get everything done by polling them ...I hope ...and I don't think it would be a lot of data to each device but I imagine overall it may be. I want to control each device at the "same" time, all with the same cabling distance (around 2m). From what I can tell, a CANbus  is exactly what I need, where I can assign a unique ID to each device (node) and then write some code to control the network array.

In summary, is a CANbus the ideal bit of hardware here to work with an Arduino to control in real time such a high number of devices?

Thanks,
Nick.

Edit: Sorry for the vagueness, I'm very new to all this so really just looking for keywords to help scope my project out before asking more complex specific questions. It's difficult to formulate what's in my head to experienced people without sounding like a goose. I'm experienced on the software side, but the hardware i/o is all brand new.

Ultimately, I am wanting to sample a grey scale image/sequence of images and depending on the value sampled in a 0-255 range which is mapped to the extension capabilities of each actuator to extend/contract in that pixel.

Hope that is more helpful. Thanks.

This is just a suggestion, certainly not the only possible approach.

Step 1: Get a handful of small linear actuators with a builtin
controller. Some actuators have no controller, and will require one
H-bridge and one analog input each. You do not want these. I have seen
some actuators with built-in controllers that can be driven just like
servos, I would suggest you get some of those. At this point you should
carefully look at costs when choosing the actuators.

Step 2: Learn how to drive those actuators from an AVR-based
Arduino, like an Arduino Uno, using the Servo library. I believe you can
drive up to 12 actuators with a single Arduino.

Step 3: Drive them using two Arduinos in a master-slave
configuration. The master would be a beefy Arduino, like a Mega or a
Due. It would send commands to the slave using, say, an I2C bus. After
sending the set points for the actuators, it would send a "go" order to
the I2C broadcast address. The slave would be the Uno. It would
interpret the commands and actually drive the actuators.

Step 3b: Change the master's program to pretend it is controlling
many slaves, and a total of 1000 actuators. In reality, all the
slaves would have the same I2C address: that of the unique slave
actually available. This will tell you whether your master is powerful
enough for the job, and you will see how the performance scales.

Step 3c: Optimize the slave's code. Try to have it work with an
8 MHz clock, and use as little flash and RAM as possible.

Step 4: Replace the slave Arduino with a bare AVR chip. You will
have to learn how to program it via ISP, but the information is widely
available. An Uno is an ATmega328P at heart, but depending on the
program size, you may get away with an ATmega48A, which is the same
thing only with less memory, and dirty cheap. Or even with a still
cheaper ATtiny. If you can make your program work with an 8 MHz
clock, then use the internal oscillator, which will save you having to
buy an external resonator. All this is to keep the costs reasonable.

Step 4b: Test, test, test. Last chance to change your mind before
committing big bucks.

Step 5: If everything works at this stage, it's time to scale up.
The same master Arduino, and one bare AVR for each dozen actuators, each
with it's own I2C address.


tty doesn't list ttyUSB0 so arduino doesn't list serial ports Okay so lsusb gives
Bus 002 Device 019: ID 1a86:7523 QinHeng Electronics HL-340 USB-Serial adapter

dmesg|grep 'ttyUSB' gives

[63723.589107] usb 2-1: ch341-uart converter now attached to ttyUSB0

but tty lists only /dev/pts/0 although in /dev there is a ttyUSB0 file (or whatever it is because vim says its not a file)

I can use cu -l /dev/ttyUSB0 -s 9600 and transmit to arduino nano as the rx LED blinks. On starting arduino I get the "java.lang.NullPointerException thrown while loading gnu.io.RXTXCommDriver" error.

System: Linux Mint 19.1 Tessa (64 bit)

Sorry, I was using the software center to get arduino IDE and that didn't work well. Downloading the official IDE from arduino.cc worked without hassle. Lesson learnt: Not all linux distros have package repos as up-to-date as Arch. :P


Which board's bootloader is on the microcontroller? Currently I'm doing a project that needs an Atmega2560 standalone MCU. After I burned the bootloader with this method: http://www.gammon.com.au/bootloader . I set the Board as "Arduino/Genuino Mega or Mega 2560" and the Processor as "ATmega2560 (Mega 2560)". But, it just stuck at "uploading" and this message pop up: "avrdude: stk500v2_ReceiveMessage(): timeout". So, I'm guessing I'm choosing a wrong board. Is there a way to check which board to select in the Tool tab?

It depends on which bootloader you loaded, when you write your bootloader with AVRDude you specify the hex file, Which Hex file did you specify?


NodeMCU V3 + SD Card with Arduino IDE Not working I am trying to connect CATALEX MicroSD Card adaptor to new NodeMCU V3 and PIN configuration are as below,

NodeMCU  ---------> SD Card
GPIO13 (D7) ------> MOSI
GPIO12 (D6) ------> MISO
GPIO14 (D5) ------> SCK
GPIO15 (D8) ------> CS
VCC (3.3V) -------> VCC
GND --------------> GND

Tested above setup with QuickStart program from SdFat library in Arduino IDE. But it gives error output as below,

SPI pins:
MISO: 12
MOSI: 13
SCK:  14
SS:   15

SD chip select is the key hardware option.
Common values are:
Arduino Ethernet shield, pin 4
Sparkfun SD shield, pin 8
Adafruit SD shields and modules, pin 10

Enter the chip select pin number: 15

Disabling SPI device on pin 10
Can't access SD card. Do not reformat.
No card, wrong chip select pin, or SPI problem?
SD errorCode: 0X20,0XFF

SD initialization failed.
Do not reformat the card!
Is the card correctly inserted?
Is chipSelect set to the correct value?
Does another SPI device need to be disabled?
Is there a wiring/soldering problem?

errorCode: 0x20, errorData: 0xff

  chipSelect is 15.

Also, I am using SanDisk 16GB Micro SDHC class 4 Memory Card.

I have tried googling with the error but did not find solution. Please help me.

If you are giving power to nodemcu through USB cable. SD card VCC can be connected to the VIN pin of nodemcu ESP8266. I faced the same problem
NodeMCU V3 + SD Card with Arduino IDE Not working
but after connecting VCC of SD Card to VIN pin of nodemcu. it worked.
Thanks for the helping me Mr. Juraj


Issue in long ON OFF timer using millis() I have 3 components: a relay and two LEDs...I want two timers using Arduino... In timer one, relay should be off on; one LED is off; and other is on...In second timer, relay is off; one led is on; other is off...
This is my Code:

//const unsigned long onTime = (2 *3600000); // 2 Hours in miliseconds;
const unsigned long onTime = (3 *1000); // 3 seconds;
//const unsigned long onTime = (5 *60000); // 15 minutes;

//const unsigned long offTime = (0.5 *3600000); // 1/2 Hours in miliseconds;
const unsigned long offTime = (2 *1000); // 1 seconds;
//const unsigned long offTime = (5 *60000); // 5 minutes;

const unsigned long start_delay = (5 *60000);  // 5 minute in miliseconds

// Tracks the last time event fired
unsigned long previousMillis=0;

// Interval is how long we wait
int interval = onTime;

// Used to track if relay should be on or off
boolean relayState = true;

void setup()
{
  pinMode(13, OUTPUT); //Relay
  pinMode(3, OUTPUT); //LED Green for ON
  pinMode(4, OUTPUT); //LED Red for OFF

  digitalWrite(13, LOW);   // Relay Off
  digitalWrite(3, LOW);    // Green LED off
  digitalWrite(4, LOW);    // Red LED OFF

  //delay (start_delay);  // wait for 5 minute
}
void loop()
{
  if (relayState == true)
  {
    // Relay ON
    digitalWrite(13, HIGH);   // Relay ON
    digitalWrite(3, HIGH);    // Green LED ON
    digitalWrite(4, LOW);    // Red LED OFF
  }
  if (relayState == false)
  {
    // Relay OFF
    digitalWrite(13, LOW);   // Relay Off
    digitalWrite(3, LOW);    // Green LED Off
    digitalWrite(4, HIGH);    // Red LED On
  }

  // Grab snapshot of current time, this keeps all timing
  long currentMillis = millis();

  // Compare to previous capture to see if enough time has passed
  if ((unsigned long)(currentMillis - previousMillis) >= interval)
  {
    // Change wait interval, based on current relay state
    if (relayState)
    {
      // Relay is currently on, set time to stay off
      interval = offTime;
    }
    else
    {
      // Relay is currently off, set time to stay on
      interval = onTime;
    }
    // Toggle the relay's state
    relayState = !(relayState);
    // Save the current time to compare "later"
    previousMillis = currentMillis;
  }
}

Now issue is; when I make timer for seconds like OnTime is 3 second and offTime is 1 second... It works perfect... But timer for hours or minutes does not simply works... it does not switch state from on to off... It constantly remains on... What could be  the problem... Thanks!

You declare interval as an integer, while onTime and offTime are unsigned long.

Change int interval = onTime; to unsigned long interval = onTime;

The maximum value of int is only 32767 (215-1), which is only 33 seconds.

An unsigned long can be as high as 4294967296 (232-1). Which is around 49.7 days worth of milliseconds.


Photoresistor value drops when board stacked on Arduino Uno I have a simple photoresistor displaying values on a serial monitor every second so I can establish a value that I want to use to have it activate a relay.

It has worked fine for a few weeks, with bright sunlight values about 1000, total dark is 0. I soldered only the headers on a protoshield, and stacked it on the Arduino. I have nothing else on the protoshield and I am still using jumper wires to a breadboard, which I have not changed.

Why would the photoresistor values drop to approximately 40 (from 900's) when I stack the second board on the Arduino?

It should not happen.

I have changed this answer, because at first I read that the resulting value was changed by -40, but I think it drops from 900 to 40.

The shield is doing something, so it is not empty. Perhaps it shortcuts the AREF to GND. Perhaps you are reading an open input, and the sensor is at another analog pin. Perhaps the shield does something to the voltage pins.

A breadboard can have bad contacts. The shield can have bad contacts.

Be sure that the sensor is connected to the channel that you are reading. Measure the voltage at that analog input with a multimeter with and without the shield. Check the 5V, 3.3V and AREF pins with and without the shield.


How do I make LEDs lights up one by one according to how long the button was pressed and hold In my project, I am trying to create a timer display with LEDs base on how long a button was pressed and hold.
There are 8 LED lights in total, when the toggle button was pressed, 1st LED lights up; keep holding/ pressing the button, the 2nd LED lights up after 1sec, the 3rd LED lights up after 2sec and so on. So 7s after the button was pressed and hold, all 8 LEDs shall light up. When the button was released at anytime, all LEDs would be off.
Something is wrong with my code which the timer seems not working (saving the time when the button was pressed) and calculate the time difference ("current time" - "time when button pressed") in order to lights up the LED.
My codes:
 int current;
 long millis_held;
 long prev_secs_held;
 unsigned long firstTime;
 byte previous = LOW;

 const int buttonPin = 13;

 void setup() {
 pinMode(buttonPin, INPUT);
 pinMode(2,OUTPUT) ;
 pinMode(3,OUTPUT) ;
 pinMode(4,OUTPUT) ;
 }

 void loop() {
 current = digitalRead(buttonPin);

 if (current == HIGH && previous == LOW) {
 firstTime = millis();
 digitalWrite(2, HIGH);

 millis_held = (millis() - firstTime);

 if (millis_held >= 1000 && firstTime <2000){
 digitalWrite(3, HIGH);
 }

  if (millis_held >= 2000){
  digitalWrite(4, HIGH);
 }
 }

 else {
 digitalWrite(2, LOW);
 digitalWrite(3, LOW);
 digitalWrite(4, LOW);
 }
 }

Hope you guys can help, thanks a lot.

There are multiple errors in your code.
In the loop, the first if might not have the use you intended it to have. You are checking for previous == low, but you never set previous to high. Therefore this check can be removed entirely, or you could restructure your code a bit and add a previous = high.
Secondly, this if is also flawed:
if (millis_held >= 1000 && firstTime <2000){
    digitalWrite(3, HIGH);
}

You are checking for firstTime < 2000 which means you need to press the button within 2 seconds of the power-up of the Arduino or else this code will not run.
Lastly, for this to run you probably only want to set firstTime = millis() once when you press the button, and not every time the loop() runs thereafter while you keep the button pressed. You would need to move the bracket on line 32 to line 22, that is from just above the else to the line above millis_held = (millis() - firstTime); and then add previous = HIGH; in the first if.
I am leaving it to you to fix your code, since that would be good practice to get some feeling for it. Happy coding!
Lastly you still need to add the last 5 leds, but once the first few work you should be fine.


Communication between two Arduinos over RF module I want to communicate Arduino A to Arduino B by using RF module. But my RF module (Tx- XLPCF20, Rx- XY-R01A) only consist of 4 pins of data pin where it can send 4 bits of data only. So, I want to develop a new encoding to send data by using 4 bits of data. How should i do for the coding since I don't want to use serial write for coding. Any suggestion? Help me please. If u can give me the coding, I'm beyond thankful.

You have 4 channels of raw HIGH/LOW communication.  How you use them is up to you.

The simplest method is to use an asynchronous serial protocol:

Use Serial: Connect the TX of one Arduino to channel 1 at the TX, and RX channel 1 to RX on the other Arduino
Use SoftwareSerial: The same as above but you choose the pins
Use VirtualWire: very similar to SoftwareSerial

For higher speeds, since you have 4 channels, you could use a synchronous serial communication protocol. It should be perfectly possible to connect three of the channels to SPI and communicate as if it were talking directly to an SPI device - one channel to SCK, one to MOSI and one to SS. The other end has SCK, MOSI and SS but running in slave mode.

No need to "invent" a 4-bit protocol, it's too much work.


Why isn't ESP8266 connecting to wifi when calling yield()? I'm experimenting with ESP8266 and I want it to cycle through various states: LED on/off, WiFi on/off and measure the connection time, deep sleep.

I wrote the following script, using millis() to define the time intervals. I cut away the previous parts of the code to have a minimum test case.

I read that ESP8266 has the watchdog automatically on, so I used yield() when spending time waiting, instead of using an empty while loop. I didn't use delay() because it block further execution of the code, and I tend to avoid it. I know it would reset the watchdog too.

#include <ESP8266WiFi.h>

const char* ssid = "wifi";
const char* password = "pass";

const int led = 2;

void setup(void){
  unsigned long refTime;

  pinMode(led, OUTPUT);
  Serial.begin(115200);
  digitalWrite(led, 1);

  refTime = millis();
// isssue from here
  while ((millis() - refTime) < 3000) { yield(); }
// to here

  Serial.println("Connecting...");
  refTime = millis();
  WiFi.begin(ssid, password);
  Serial.println("");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  // never gets here when "issue" code enabled
  Serial.println(millis() - refTime);
  digitalWrite(led, 0);
}

void loop(void){

}

If I use the yield(), then I never get a WiFi connection (well, it happened only once, actually).

Why is yield causing issues?

Insert refTime = millis(); inside while loop.


Purposely create compile error to fail the upload I would like to create a compile error so sketch does not upload in certain cases.

I have written a library with a function that adds pins being used to an array. If the same pin is used twice I want to fail the compilation (preferably with an error that explains why). Is this possible?

void CheckPinNum(int newPinNum){
  for (int i=0; i <= PinArrayLength; i++){
    if (newPinNum == PinArray[i])
      failCompilation("You entered same pin twice!");
  }
}

To answer the question asked in the title:

#if some_condition
# error Some error message
#endif

But note that this technique only works at compile time, which
probably makes it useless for you.


Gas Sensor output voltage to concentration I am using figaro tgs gas sensor (2600, 2602 and 2620) to sense breath from human. What I obtained is the output voltage. However, I would like to convert the voltage to concentration in ppm? Since these gas sensors can sense more than one gas. Is there any way?? Thanks.

I would like to convert the voltage to concentration in ppm?
Is there any way??

the datasheet for those devices would have the answers for you. Generally, you read the datasheet BEFORE deciding on using them or not. not that otherway around.


SD Card shield and TCRT5000 sensor aren't working together on arduino uno I need to work with SD card and TCRT5000 sensor (Reflective Optical Sensor with Transistor Output) and save data from sensor to file. So I select Arduino Uno and added to it a SD card shield(from LC STUDIO) and a TCRT5000 sensor but it isn't working.
My circuit and code is here:

#include <SPI.h>
#include <SD.h>

const int chipSelect = 10;

void setup() {
  Serial.begin(9600);
  pinMode(chipSelect, OUTPUT);
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    while(true);
  }
  Serial.println("card initialized.");
  File dataFile = SD.open("test.txt", FILE_WRITE);
  dataFile.close();
  dataFile = SD.open("test.txt", FILE_WRITE);
  if(dataFile){
    dataFile.println("Start:");
  }else{
    Serial.println("Error in creating file.");
    while(true);
  }
}

void loop() {
  float value = analogRead(A3);
  File dataFile = SD.open("test.txt", FILE_WRITE);
  if (dataFile) {
    dataFile.println(value);
    Serial.println(value);
    dataFile.close();
  }else{
    Serial.println("Error in opening file.");
  }
  delay(5);
}

When TCRT5000 isn't connected SD card working without any problem.
I think it is related to current and supply current. Any idea?

Did you figure this out yet? If not, you have the +5 volts going to the GND on the breadboard, causing a short.


Is it possible to program an ESP8266 12F using an Arduino Nano? I just got my ESP8266, but I am unable to program it. Since it can't be connected to via USB, I was wondering if I can program it using an Arduino or perhaps use it as a shield for an Arduino Nano. I haven't been able to find a good guide online. Any help is greatly appreciated.

Yes, you can program it with Arduino but its a bit complex that way. You will need a separate Linear Regulator with Adjustable Output to get it hooked up with the Arduino.
 Its way better to have an FTDI adapter to program it.

But if you still want to know, there is a tutorial below,

Upload Bareminimum sketch so that no program is running on the Arduino.


Problem with if condition So my project is including detecting the temperature in the room by using dth11 sensor.
my idea is to add 3 LED lights were each light represent the temperature if its cold or hot or perfect.

the wiring and coding is done and it's working .However, i'm having a problem were the perfect temperature is always on no matter if the temperature is hot or cold.
example: if the temperature is cold the cold LED will blink and the perfect temperature LED will be on.

#include <Adafruit_Sensor.h>
#include <DHT.h>
#define DHTPIN A0
#define DHTTYPE DHT11
#define LED_TOO_COLD 6
#define LED_PERFECT 8
#define LED_TOO_HOT 7
DHT dht(DHTPIN, DHTTYPE);
void setup() {
  Serial.begin(9600);
  Serial.println("DHT11 test!");

  dht.begin();
}

void loop() {

  pinMode (6 , OUTPUT);
  pinMode (7 , OUTPUT);
  pinMode (8 , OUTPUT);
  delay(2000);

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

  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.println(" *C ");
  if (t < 22) {
    Serial.println("Too cold!");
    digitalWrite(6, HIGH);
    digitalWrite(7, LOW);
    digitalWrite(8, LOW);
    delay (2000);
  }
   if (t >26) {
    Serial.println("Too hot!");
    digitalWrite(7, HIGH);
    digitalWrite(6, LOW);
    digitalWrite(8, LOW);
    delay (2000);

  } else {
    Serial.println("Perfect temperature!");
    digitalWrite(8, HIGH);
    digitalWrite(6, LOW);
    digitalWrite(7, LOW);
    delay (2000);
  }

}

firstly, move your pinMode() settings to setup section.

in your code, when the temperature is 21 active pin will be 6 and 8.
you should rewrite your code in next ways:

1:

if (t < 22) {
  ... its cold temp ...
} else if (t > 26) {
  ... its hot temp ...
} else {
  ... it's nor temp ...
}

2:

if (t < 22) {
   ... its cold temp ...
}
if (t > 26) {
   ... it's hot temp ...
}
if (t >= 22 && t <= 26) {
   ... it's nor temp ...
}

and my small advice for u, rewrite in this way, it is more readable

digitalWrite(6, HIGH);
digitalWrite(7, LOW);
digitalWrite(8, LOW);

digitalWrite(6, LOW);
digitalWrite(7, HIGH);
digitalWrite(8, LOW);

digitalWrite(6, LOW);
digitalWrite(7, LOW);
digitalWrite(8, HIGH);

visually changing ENUMS (like LOW or HIGH) more noticeable than changing numbers (6/7/8)


Switching low current AC What is the simplest way to switch ON/OFF a 60v and 5 mA of current ?
I don't want the common relays for arduinos as they make click noise.

// Following devices could be helpful in you case.

Power BJT as a switch (check datasheets if it comes on your required range).
Solid state relay is obviously, but cast is little high in this case.


Whats wrong with my POST request? Ive been trying to get POST working on my ESP8266. I followed this tutorial https://techtutorialsx.com/2016/07/21/esp8266-post-requests/ which works, but once i change the request URL to anything else i get -1 response from http.POST() which the library returns when "no info".
I have no clue what the "no info" means and what im doing wrong. Does anyone have any suggestions? Below is the code im using.
if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status

    HTTPClient http;    //Declare object of class HTTPClient

    //http.begin("http://192.168.1.88:8085/hello"); //Works fine
    //http.begin("https://httpbin.org:8080/post"); //Causes -1 as httpCode
    //http.begin("https://httpbin.org/post"); //Causes -1 as httpCode
    http.begin("https://XXXXX.execute-api.eu-west-2.amazonaws.com/XXXXX/XXXXX");
    http.addHeader("Content-Type", "application/json");  //Specify content-type header

    int httpCode = http.POST("{\"key\":\"1\",\"id\": \"ESPXXX2\",\"action\": \"rbg\",\"value\": \"255255000\"}");   //Send the request
    String payload = http.getString(); //Get the response payload

    Serial.println(httpCode);   //Print HTTP return code
    Serial.println(payload);    //Print request response payload

    http.end();  //Close connection

  } else {

    Serial.println("Error in WiFi connection");

  }

  delay(10000);  //Send a request every 10 seconds

Only serial output im getting is "-1" for httpCode and empty line for payload.

I ended up ditching HTTPS since it doesnt seem to be implemented all that well (Requires hardcoding of fingerprint).
Changed the architecture of my system so that HTTPS is handled by Python which doesnt require jumping through hoops.


Can the Arduino Eclipse plugin v2.2 be used with Arduino 1.5.8? It keeps giving me this warning:

  You are using a version of the Arduino IDE that is newer than available at the release of this plugin.`

Does this means I need to use a night build?

V2.2 is pretty old by now.
As far as I recall it should work fine.

V2.2 of the Arduino eclipse plugin should work fine with the Arduino IDE version 1.5.8.
What that phrase wants to say is: the plugin V2.2 was released before Arduino IDE 1.5.8 was released; as such the code can not make a statement on the compatibility.

But again V2.2 is old. We hope to release V3.0 end of February 2016


Power Supply Problem with Arduino Yún: Using a log USB cable I want to use an Arduino Yún as a kind of outdoor weather station. I want to supply the power for the Yún with a 5V USB-Charger. Using a normal USB cable everything works fine. But as the weather station shall be far from the next power socket, I made the USB cable about 10 meters longer. Now the Yún does not power up any more.

Has anybody an idea why?

Should I use a 12 V power supply and a 7805 power converter instead?

The USB specification limits the length of a cable between two devices to 5 meters. When you make a longer cable, you're going out of spec, which means it is not guaranteed to work anymore.

Since you're only supplying power, the issue is (as you have guessed) the voltage drop in the cable. However, the voltage drop will depend on how much current Arduino is consuming at any given moment. Supplying it with a higher voltage without a converter is dangerous, because it will lead to overvoltage you won't be able to control.

I'd suggest trying better cables first: thicker and stiffer cables have thicker wires, and may have less voltage drop. You can also make your own cable (provided you can solder) using only two thick wires for power.

The ultimate solution, like you said yourself, is to deliver higher voltage over the wire (12V would do) and install a power converted (12V to 5V) near your Arduino. That way, the voltage drop in 5V line will be small, and the voltage drop in 10m 12V line will be compensated by the converter. Actually, the intermediate voltage may be higher: you can simply drop a mains line (220V or whatever you have) to your weather station and place the same USB charger near the Arduino.


How to communicate from Python to Arduino Softserial That is driving me nuts so I need your help.

Master : PC with Ubuntu, a USB to serial converter (chipset CP2102), connected to Arduino Uno Pin 10, 11 and GND. The Arduino Uno is plugged in the same PC.

Port for the converter is /dev/ttyUSB1
Port for the Arduino is /dev/ACM0

I tried to communicate by Serial through the converter (I do not want to use ACM0 as it is buggy and sometimes suddenly change to ACM1, messing up my big testing program).

On Arduino side :

#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11);
int inByte = 0;         // incoming serial byte

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

void loop() {
  if (mySerial.available()) {
    char inByte = mySerial.read();
    mySerial.println(inByte);
    Serial.println(inByte);
  }
  delay(10);
}

The Python script (simple one to debug)

import serial
arduino = serial.Serial('/dev/ttyUSB1', 9600)
arduino.timeout=0.5
arduino.bytesize=8
arduino.stopbits=1
code=49 #ASCII Code for 1
arduino.write(chr(code).encode('utf-8'))
print(chr(code))
print(chr(code).encode('utf-8'))
print(arduino.readline())
print("done")
arduino.close()

When I run it, I have on Arduino Serial monitor a g

and Python script output

1
b'1'
b'Ly\x00'
done

By the way, the very same code over /dev/ttyACM0 and standard serial rather than Softwareserial works perfectly (as long as the port remains ACM0 of course)

That is all me, look for an answer for ages, finally post a question, to end up finding the answer in the following hour...

this is because Arduino takes TTL as input and not RS-232...

similar here :
https://electronics.stackexchange.com/questions/42584/arduino-uno-weird-characters-sent-to-com-softwareserial


Sound sensor only detect peaks I'm using this SparkFun Sound Sensor in my project for a simple ambient sound meter.

I'm just trying to monitor the raw analog envelope output for the moment.

My problem is that the output only changes with peak sounds, like a clap in my hands for example. But when the ambient sound is louder, people talking or loud music, the output doesn't change.

It seems you have to increase the gain, see inside the document

Sound dectector hookup guide

The following fragment:

Also take into account it needs between 3.5 and 5.5 V, while 5 V is ideal (see Quick start at the beginning of the same document.


Reset a UART connection on a Due I have a system that involves an Arduino Due connected to a Raspi 4 through UART in which the Due sends a heartbeat signal over UART for the pi to receive and send back as confirmation. One of the events that I need to handle is re-establishing the UART connection between the two devices if the program receiving UART on the pi (or the pi itself) fails for any reason and reboots. At the moment, I have the initial heartbeat working (as long as the pi program starts first) but when I stop the pi program to simulate a fatal error and restart it, the Due doesn't seem to receive heartbeat confirmation until it's reset as well.
Is there a clean way to reset just the one Serial connection from the Arduino script? I thought of using Serial.end() and Serial.begin() but that's really ugly and I'd prefer to avoid it. None of the other Serial library methods seem to provide the ability to reset the connection.
I'm using Serial2 at 115200 baud.
Edit: Including relevant heartbeat code:
#include <DueTimer.h>

bool heartbeat = true;

void rx_heartbeat() {
  int received_data;

  if (Serial2.available() > 0) {
    received_data = Serial2.read();
    heartbeat = true;
    Serial.println("beat");
  }
}

void setup() {
  Serial2.begin(115200);
  Timer1.attachInterrupt(heartbeat_ISR).setFrequency(1).start();
}

void loop() {
  rx_heartbeat();
}

void heartbeat_ISR() {
  if (heartbeat) {
    heartbeat = false;
  } else {
    // no heartbeat returned - stop normal operation
  }
  Serial.println("heart");
  Serial2.write(255);
}

Silly me forgot to actually upload the code that fixed my issue. The code shown in the question is correct and works as intended.


Arduino MKR 10100 control DC Motor Thank you for reading my post. I have been stuck on this for several weeks now! I am trying to turn ON/OFF a DC motor from Arduino IOT Cloud. I have set up the cloud and added the switch. Everything works well with an LED: it lights on and off as needed, but the motor does not turn on or off. Below is the circuit I have set up.

My circuit specs are as follows:

I'm not using a UNO as the image illustrates, rather I'm using an Arduino MKR WiFi 1010, but the connections of the pins are exactly the same: LED at PIN 3 and Motor at 7.
The diode I am using is 1N4001.
The transistor I'm using is TIP120.
The motor I'm using is 5V DC Motor.
270 Ohm resistor on the transistor circuit and 220 Ohm on the LED circuit.

The Arduino code I made is as follows:

#include "thingProperties.h"

#define LED_PIN 3
#define MOTOR_PIN 7

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

  setDebugMessageLevel(2); // For debugging of cloud integration
  Serial.begin(9600);
  delay(1500);

  initProperties(); // initialize cloud properties
  ArduinoCloud.begin(ArduinoIoTPreferredConnection); // Connect to cloud
}

void loop() {
  ArduinoCloud.update(); // Update cloud background services
}

void onMotorChange() {
  if (motor) {
    // Motor & LED ON
    digitalWrite(LED_PIN, HIGH);
    digitalWrite(MOTOR_PIN, HIGH);
  } else {
    // Motor & LED OFF
    digitalWrite(LED_PIN, LOW);
    digitalWrite(MOTOR_PIN, LOW);
  }
}

All my setup seems to be be correct, but it just is not working. I have researched a lot but to no avail. I have tested with a different motor just to be sure, but it also does not work. I'm not sure where I have made a mistake.

Please help me. Thank you very much.

The TIP120 is a poor choice because of the approximate 10% - 14% voltage drop across it. Try the circuit with a logic level, low Rds MOSFET.

For a more in-depth answer, please see this answer: https://electronics.stackexchange.com/a/388468/165322


Will this SensorHub work? As a project I have to build a SensorHub with multiple sensors. I am relatively new to the Arduino and circuit world, so I need a little help.

The Goal is to build hub with multiple sensors and to be able to measure power consumption of the entire thing and log the data from all sensors.

So I came up with the following part list:

Arduino Uno (Rev3)
Adafruit 10-DOF IMU L3GD20H + LSM303 + BMP180
Adafruit Ultimate GPS v3
Adafruit VCNL4010 Proximity and Light sensor
Adafruit INA219 High Side DC Current Sensor Breakout
Adafruit MicroSD card breakout board
of course breadboard, powersupply, calbes, etc.

Everything is connected like this:

My question is now if this thing will work as I expect. With the 10-DOF, GPS and VCNL4010 I'm pretty sure. They work all with I2C on different addresses and all of them need 5V.

The question is now if I can measure the needed power with this setup. Or does the INA219 need power to be able to get the power to the Arduino? Do you see any problems?

The INA219 breakout will pass current, even if it doesn't receive any power itself.


I2C broadcast and reply on Arduino M0+ I am trying to set up several ATSAM-based AVR chips in a master/slave broadcasting arrangement. I want the master to be able to send a broadcast message to I2C address 0, and then for slaves to respond with different information. I have seen other implementations where this has been successful since I2C devices will typically self-arbitrate and if they are configured to back-off when arbitration is lost, the master can repeat its request and iterate over all addresses on the bus.

The challenge is that while I have Wire.beginTransmission(0) working to reach my slaves from the master, I cannot get Wire.requestFrom(0,6) to work. The slave acts as though no message had arrived in the reply case. This is in the reduced case of one master and one slave.

In the example below, changing RequestFrom to the slave address will work.

I am aware that on the SAMD architecture, ArduinoCore does not configure the SERCOM for I2C broadcasts so I made a one-line modification as follows to enable it:

sercom->I2CS.ADDR.reg = SERCOM_I2CS_ADDR_ADDR( ucAddress & 0x7Ful ) | // 0x7F, select only 7 bits
                      SERCOM_I2CS_ADDR_ADDRMASK( 0x00ul ) |
                      SERCOM_I2CS_ADDR_GENCEN // added by JAG

My master code:

#include <Wire.h>

void setup() {

  Serial.begin(9600);
  Serial.println("Sketch start" );

  Wire.begin(); // join i2c bus (address optional for master)
}

byte x = 0;

void loop() {

  Serial.print("-- Top of loop:" );
  Serial.println( millis() );

  Wire.beginTransmission(0); // transmit to device #8
  Wire.write("x is ");        // sends five bytes
  Wire.write(x);              // sends one byte
  Wire.endTransmission(true);    // stop transmitting

  // delay( 500 );

  uint8_t recvSize = Wire.requestFrom(0, 6);    // request 6 bytes from slave device #8

  Serial.print( "Got bytes: " );
  Serial.print( recvSize );
  Serial.print( "---> ");

  while (Wire.available()) { // slave may send less than requested
    char c = Wire.read(); // receive a byte as character
    Serial.print( "[") ;
    Serial.print(c);         // print the character
    Serial.print( "]" );
  }
  Serial.println();

  x++;
  delay(500);
}

My slave code:

#include <Wire.h>

void setup() {
  Wire.begin(9);                // join i2c bus with address #8
  Wire.onReceive(receiveEvent); // register event
  Wire.onRequest(requestEvent); // register event
  Serial.begin(9600);           // start serial for output
  Serial.println( "Starting up" );
}

void loop() {
  delay(500);
    Serial.print( "In top of loop (slave): " );
    Serial.println(millis() );
}

// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany) {
  while (1 < Wire.available()) { // loop through all but the last
    char c = Wire.read(); // receive byte as a character
    SerialUSB.print(c);         // print the character
  }
  int x = Wire.read();    // receive byte as an integer
  SerialUSB.println(x);         // print the integer
}

// function that executes whenever data is requested by master
// this function is registered as an event, see setup()
void requestEvent() {
  Wire.write("hello"); // respond with message of 6 bytes
  // as expected by master
  Serial.println( "<<<< Writing a response." );
}

If you broadcast data using Wire.send(data), the slaves would receive this in there onReceive handler but as far as I can remember, the I2C slave will not respond on a Wire.requestFrom(...) broadcast from the master.

Imagine x slaves responding all at the same time to the request...


Arduino and 2 Adafruit Fingerprint modules working together I want to do a project with fingerprint access control. But my client wants one on both sides of the door (inside and outside). Now I am using this product Adafruit Fingerprint module but I don't want to enroll each person on each fingerprint module. I want to look at enrolling each employee on 1 of these modules and then via arduino "SYNC" the fingerprint models between each other. Is this possible? Can someone maybe point me in the right direction or am I just insane HAHAHA. Look I can do the route of programming/enrolling each person on each module. But we life in a real world and at some point the fingerprint model/id's are not going to match up. And then there is going to come a problem with my online software. As well sorry for my bad lanuage  :)

Yes, you can easily do that. This finger Print sensor works over Serial communication.

You can have multiple Serial devices connected to your Arduino UNO using SoftwareSerial library.

All you have to do is to create multiple instances of Adafruit_Fingerprint initialized with different SoftwareSerial objects. i.e.

// pin #2 is IN from sensor1 (GREEN wire)
// pin #3 is OUT from arduino to sensor1  (WHITE wire)
// pin #8 is IN from sensor2 (GREEN wire)
// pin #9 is OUT from arduino to sensor2  (WHITE wire)
SoftwareSerial mySerial1(2, 3);
Adafruit_Fingerprint finger1 = Adafruit_Fingerprint(&mySerial1);
SoftwareSerial mySerial2(8, 9);
Adafruit_Fingerprint finger2 = Adafruit_Fingerprint(&mySerial2);

Now, you can use finger1 and finger2 for your finger print operations. (previously referenced as only finger)

In order to understand Serial Communication with multiple serial devices, have a look at this Arduino.cc Offical tutorial.

Hope it helps.


No valid serial ports for Arduino UNO on Mac UPDATE: The issue turned out to be with my work laptop. Our IT department has them configured in such a way that the assignment of serial ports is different somehow. When I plugged in on my personal Macbook Pro it all worked perfectly.

I just got my first Arduino. Its an UNO R3. I'm running OS X 10.8.5 (Mountain Lion) and the Arduino IDE 1.0.5

Under Tools>Board I have Arduino Uno selected

Under Tools>Serial Port my options are:

/dev/tty.Bluetooth-Serial-1
/dev/cu.Bluetooth-Serial-1
/dev/tty.Bluetooth-Serial-2
/dev/cu.Bluetooth-Serial-2
/dev/tty.Bluetooth-Modem
/dev/cu.Bluetooth-Modem
/dev/tty.Bluetooth-PDA-Sync
/dev/cu.Bluetooth-PDA-Sync

I've tried all of them, but when I try to upload a sketch it fails. Most give the following error:

avrdude: stk500_recv(): programmer is not responding

The two "modem" options return this message:

Serial port '/dev/tty.Bluetooth-Modem' already in use. Try quitting any programs that may be using it.

I'm at a loss. None of these serial ports seems correct but there aren't any other options.

Also under Tools>Programmer which option should I be using?

Have you hooked up your Arduino prior to pulling down the tools>Serial Port menu? I only see the port for my Arduino listed when it's actually connected and running. (And it's never one of the bluetooth ports.) I don't have my Arduino with me at the moment so I can't tell you exactly what it is.

Also note that on my MBP (running 10.9.4) I have to be sure to plug the USB cable into the CORRECT USB port. The other port maps to a different port in the list of serial ports.


Arduino secure two way communication over radio I would like to implement a secure communication channels between 2 arduinos communicating over 433 mhz radio modules (to be more precise using the barebone Atmega 326 chips).

I know that the lack of resources are a problem with the Atmega chips. The best starting point I could find was this library, which never got written:

https://forum.arduino.cc/index.php?topic=314845.0

The way I see it it does not matter what kind of encoding we use if an attacker can capture and replay that OTA, there has to be a 2nd component between the devices which is not known for an attacker and changes the same way like a DS based timer. If a client could encrypt its messages using key=timeXpassword key->encrypt(datatobesent) then the server could decrypt it the same way if it arrived in a proper time period like +-/5 seconds where the time does not have to be the current accurate time just a clock which is in sync between the devices. When the message is received by the server it would calculate 5 different data possibilities for the 5 seconds and look into a decrypted data for certain string to determine if that is a VALID data packet.

For this again there would be the need of an external timer circuit like the DSXXXX series because the internal timer in the chip is not reliable/overflows after a while.

Any other ideas for secure communication?

You may want to take a look at my RC4-with-diffusion algorithm RC4D which is very resource friendly as it takes less than 500 bytes of flash space (when encrypting inplace) and is much faster than AES128 on an Arduino.


Converting c string to integer to unsigned char I'm Trying to grapple with types between two different libraries.
The gist is that I'm using the ArduinoWebsockets library to receive information coming from my api that I then want to render out to an LED matrix. An example message would look like this:
1
2
4
8
16
32
64
128

It's important to point out that the data here is a list of string version of numbers, not integers.
I.e. if you look at the binary version of 1 from the list it's actually 110001 which is the ascii code for the character 1.
This is because the message coming back from the websocket server is pulled out as a const char *.
The LED matrix function I'm calling has a signature of:
void Write_Max7219(unsigned char address, unsigned char dat)

So I need to send in the values as unsigned chars.
I want to:

parse this information line by line
convert the ascii character for the number into it's integer equivalent
pass the value to a different function to write the data to an LED matrix

And I'm not sure how exactly to do this. I've been grappling with the type const char pointer vs regular char pointer and how to properly parse the return delimited string.
Any help would be greatly appreciated!!
Clarification
Based on some of the comments I don't think I explained the reason I'm trying to do this conversion very well. Here's (hopefully) a better explanation:
The reason I want to convert it is because I'm not displaying the number character as a string, I want to use the binary representation to control the lights in a row of the matrix.
The number 1 or 0b00000001 would light up only the rightmost led on the 8 led row of the matrix.
The idea is that I could send over rows of numbers where each row corresponds to the row on the LED matrix.
e.g.
1   -> 0b00000001
2   -> 0b00000010
4   -> 0b00000100
8   -> 0b00001000
16  -> 0b00010000
32  -> 0b00100000
64  -> 0b01000000
128 -> 0b10000000

But the messages I get from the websocket server are coming through as the string representations of the numbers (ascii or utf) vs the numbers themselves, so I can't just pass the numbers into the function for the led matrix because the underlying binary is different.
The conversion is so that I can use the binary representation of 1 (0b00000001) vs the binary representation of '1' ( 00110001).
UPDATE AND RESOLUTION
So I've been on a big troubleshooting journey. When @ocrdu said:

BTW I would try to get the websocket to send the correct single bytes instead of string representations of numbers, if at all possible.

I thought "yeah, that's the real way of fixing it and understanding what's going on", so I started tracing the issue back. Without going into all of the detail it turns out that the problem I was having was actually starting at the test client.
I use firecamp and websocat as websocket client testing tools. I was trying to send the binary data via both tools, but when I dug in via Wireshark I found that the data in flight coming from the client itself was made up of the hex values for the encoded characters of the 1s and 0s.

After researching and asking a separate stackoverflow question I figured out a way of sending the actual binary data from the client, specifically printf.
e.g.:
 printf "\x01\x02\x03\x04\x05\x06\x07\x08" | websocat -b ws://localhost:3002

Now that this works I can start going back through the rest of my arduino code and have it parse the binary data directly instead of converting the encoded values to their binary counterpoints.
All of that said, I do appreciate all of the help. I may not have needed to do the conversions for this particular instance, but I want to get better with my C types, conversions, and general understanding so the knowledge gained here is still beneficial. Thanks everyone :bows:

Not sure if or why you want to convert char* to int, but if you need to, there are atoi(), atol(), strtol(), strtoul() to consider, or rolling your own function.
Pros and cons are discussed here. Main thing to note is that atoi() and atol() have no error handling, but if the char* you feed them is completely under control and predictable, that need not be a problem.
BTW I would try to get the websocket to send the correct single bytes instead of string representations of numbers, if at all possible.


How to program an Arduino Uno to collect data using a timer interrupt and analyze that data in matlab? I working on a project where I want to collect sensor data (from a sensor) and I want to analyze the first 20 data sample (e.g., find the range, trendline e.t.c.). I know how to compile a timer interrupt in Arduino IDE (using an ISR timer), but how would I be able to do this something similar (ISR timer) in MATLAB. The reason being, I want to collect my sensor data at exactly 20 Hz and using a delay function can prove to be inaccurate. Also, when I run a sample program that collects data in MATLAB, my sample frequencies change from 15Hz to even 24Hz (as shown below) . Does anyone have any suggestion on how I can do this? If the question is not clear enough I can elaborate more in the comments.
This is my MATLAB code:
clear all;
a = arduino('com4', 'uno');
i = 0;
v1 = zeros(1e4,1);
v2 = zeros(1e4,1);
x = zeros(1e4,1);
t = timer('TimerFcn', 'stat=false; disp(''Timer!'')',...
                 'StartDelay',5,'Period', 1);
start(t)

stat=true;
tic
while(stat==true)
   %while i<60
    i = i + 1;
    v1(i) = readVoltage(a, 'A0');
    v2(i) = readVoltage(a, 'A1');
    x(i) = i;
    disp(x(i));
    pause(.00001);

  % end
end
toc

% %Plot voltage versus time
v1 = v1(1:i);
v2 = v2(1:i);
x = x(1:i);

p = v1;
n = v2;
%Plot voltage versus time
figure(1);
plot(x,p,'-',x,n,'-')
xlabel('Elapsed time (sec)')
ylabel('v')
title('Ten Seconds of voltage Data')
%set(gca,'xlim',[t(1) t(i)])
legend('v1', 'v2');

%
delete(t) % Always delete timer objects after using them.

Output is
>> Timer
     1

     2

     3

     4

     5

     6

     7

     8

     9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    37

    38

    39

    40

    41

    42

    43

    44

    45

    46

    47

    48

    49

    50

    51

    52

    53

    54

    55

    56

    57

    58

    59

    60

    61

    62

    63

    64

    65

    66

    67

    68

    69

    70

    71

    72

    73

    74

    75

Timer!
    76

Elapsed time is 5.032553 seconds.
>>

I apologize for the long output. But as you can see, I specified a pause time of .00001, which should give me well over a 20Hz sampling frequency. But I only get 76 samples/5 seconds = 15.2Hz. Also, sometime when I run this the program may collect 79sample/5secons, or even  121sample/5seconds. It just is not consistent. I was hoping to solve this with a timer interrupt that will be hard coded in MATLAB to collect data at exactly 20Hz. Please let me know what y'all think. Thank you.

I've configured the timer differently making use of its UserData property. The timer will update the data every fixed period for a specified number of samples.
close all;
clear all;

% Some useful constants.
NUM_SAMPLES = 20;
PERIOD = 0.05;

global a;
a = arduino('com4', 'uno');

% Initialise data. It will be updated by the timer.
data.i = 0;
data.v1 = zeros(NUM_SAMPLES, 1);
data.v2 = zeros(NUM_SAMPLES, 1);
data.x = (1:NUM_SAMPLES) * PERIOD;

% Initialise timer for a fixed period for a specific number of samples.
t = timer;
t.ExecutionMode = 'fixedRate';
t.Period = PERIOD;
t.TasksToExecute = NUM_SAMPLES;
t.TimerFcn = @TimerCallback;
t.UserData = data;

% Run the timer and wait for it to complete.
start(t);
wait(t);
stop(t);
data = t.UserData;  % Retrieve the updated data.
delete(t);

% Plot voltage versus time.
figure(1);
plot(data.x, data.v1, '-', data.x, data.v2, '-');
xlabel('Elapsed time (s)');
ylabel('Voltage (V)');
title('Voltage Data');
st = sprintf("%0.3f seconds", NUM_SAMPLES * PERIOD);
subtitle(st);
legend('v1', 'v2');

function TimerCallback(obj, event)
    global a;
    obj.UserData.i = obj.UserData.i + 1;
    obj.UserData.v1(obj.UserData.i) = readVoltage(a, 'A0');
    obj.UserData.v2(obj.UserData.i) = readVoltage(a, 'A1');
end


How to connect this motor driver board to Arduino to drive bidirectional motor? I am familiar with using PWM on Arduino and have done so with simple 3-pin interfaces: e.g. PWM, DIR (direction) and GND pins. Choose a direction with DIR, set speed with PWM in software (0 - 255), simple stuff.

But this board I'm buying seems different:

http://www.ebay.com/itm/DC-43A-Double-BTS7960B-Stepper-Motor-Driver-H-Bridge-PWM-for-Arduino-Smart-Car-/141485439094

There seems to be 6 control pins:

R_IS, R_EN, RPWM, L_IS, L_EN, LPWM

But from what I understand this board would only be used for controlling one motor bidirectionally, so why is there a distinction between left and right?

So how would I go about using this motor driver board in a similar way to my PWM, DIR, GND boards that I've used before to control the motor direction and speed?

Thanks!

I guess you have used DC Motor for your earlier cases? Or Step Motor with a logic on the stepper controllers?

Here you have two H Bridges which drives one Step Motor. So as I understand it, you have two PWM Inputs, one for each output channel to the coil windings of the stepper motor. Like an encoder signal you can set the direction with setting one pwm before the other. So the step motor is controlled via unipolar stepping.

For further help you need to say which motor you want to use with this card. But first I would look at the different stepping modes (unipolar and the two bipolar and maybe microstepping).

Greets


Resistors/capacitor used in connecting 23LC1024 SRAM 1 Mbit Yesterday I received by 23LC1024 SRAM with 1 Mbit memory.

I tried to search for some libraries and ways how to connect it.

So I searched around on internet first for the connections and saw some different ways of doing it, especially regarding the pullup resistors.

E.g. in Example1 two resistors are mentioned for pin 3 and 7.
In Example 2 only one resistor is used.
In YouTube example 3 three resistors and a capacitor is used. See around 5:25.

My questions:

Is one of those three better (and why)?
Is the capacitor in the youtube example 3 connected to GND or 5v? I cannot map the schema with the breadboard since the capacitor should run between +5 and GND but I don't see the +5 or GND connection (depending on where the capacitor is connected to which I cannot see or deduce).

Btw, I got it working with the 2 resistor solution but just wondering if example 1 is good enough or example 3 is better.

It's better to use external pull-up resistor at least on CS. It's because MCU pins are configured as INPUTs without pull-ups just after the startup/restart before it gets into the setup().

Also I'd recommend decoupling capacitor as close as possible to the SRAM power supply pins (between Vcc and Gnd). You can google what the decoupling capacitors are (they are also called bypass capacitors).

Edit: First two examples are supposed to be on bread board. So it's not so hard just rewire it, if you have to use for example /HOLD too. However the third example is soldered on prototype board and therfore it's not so easy to rewire it. That's why NU and /HOLD inputs are connected to the Vcc through 10k resistor. If you have to use /HOLD in the future, it's easier to just solder new connection, than rewire hardwired connection to the Vcc.

About decoupling caps - there are even sockets with builtin cap:


SDS011 Dust Sensor Checksum Error I'm working with an SDS011 particular sensor through its serial interface. The spec sheet (http://inovafitness.com/upload/file/20150311/14261262164716.pdf) indicates that the second to last byte of a serial packet is a checksum equal to sum of all the data bytes.

I am using pyserial to read and interpret the serial data. Here's a snippet of the code:

import serial

def read_sensor(port):
    while True:
        header = port.read(2)
        if header == b'\xAA\xC0':
            data = port.read(6)
            checksum = port.read()
            tail = port.read()
            if tail == b'\xAB':
                return header + data + checksum + tail

port = serial.Serial(port=MY_PORT)
packet = read_sensor(port)
data_sum = sum(packet[2:8])
checksum = packet[8]

if data_sum == checksum:
  print('Ok')
else:
   print('Error')

However, I haven't got a single packet whose checksum hasn't been an error. Is there anything I could be potentially doing wrong?

Generally, a checksum byte is computed using 8-bit arithmetic, with overflow ignored.

The Python sum function uses arithmetic of indefinite precision (eg, 32- or 64-bit words for small values, with additional words for larger numbers).

Try comparing checksum to data_sum % 256.  If that doesn't fix the problem, print out some of the data packets and checksum values so that you can use a calculator to test different combinations.


Arduino gets stuck: battery powered, wireless, dc motor drive I have a Arduino Mega 2560 connected to

L293D Motor Driver IC connected to two small size dc motors.
MPU-9150 using i2c
Xbee v1.1 arduino shield by seeed
Li-po battery, 7.4 volts, 2200 mah.

All components are tested separately, they all are working fine, the sensor readings showing data on serial monitor, the l293 drives the motors, xbee sends wireless serial data on pc, and li-po is also working fine.

I have checked the wiring alot of times. It all seems to be correct.

The problem arises when i connect all of them together, since I am using a single power source, I power the l293d with the Li-po and the Arduino also with the Li-po.

When the L293D is powered using Li-po and it starts drawing current from the battery, the serial monitor/arduino gets stuck. It doesnt show sensor readings anymore, while the dc motors start spinning. And they continue to spin, until I break connection with the battery.
Without the l293d powered, the sensor readings are working fine, everything is going normal, as it should, but as soon as the l293d is connected, arduino is stuck..

I have searched alot of forums for this, found some info, perhaps something to do analog and digital ground? mpu-9150 is digital ground. So that is why it stops the arduino mega as the l293d starts drawing current. All hell breaks loose.

Can anybody please help me with this? it is giving me headaches ever since!

My guess is that your motors are drawing too much current and the voltage from your battery is dropping too low for the voltage regulator on the Arduino. Looking at the data sheet, the L293D will provide up to 600-mA for up to 2 motors at a time. That's up to 1.2 amps, a whole lot of current. I would suggest trying to power your arduino from a separate 9 volt battery as an experiment.


Two Arduino boards with I2C sensors I am new and lost. I have been searching the internet about how to transfer data of multiple sensors from one Arduino to another using I2C but no luck. All the codes and tutorials online focus on multiple slaves with one sensor.
The attached Fritzing is not my project, but my project involves 22 pressure sensors and I need to log their readings in Excel using plx, so the picture is just for demonstrating the idea.
The main idea is to transfer the sensors' data from the slave to the master over I2C.
I just need an answer if this doable or not plz

There's two basic ways of doing it.

Send a byte from the master to the slave first to select which sensor you want, then request the data for the currently selected sensor, or
Request lots of bytes from the slave and fill them in one at a time as the requests arrive.

The first way is the slow, but "I2C" way of doing it - basically each sensor is its own register in the slave, and you select which register you want to read from.

The second way is faster, but you have to keep track internally of where you are.

A good compromise is to implement "auto increment" which does both scenarios: if you send a byte it sets the current sensor to read from. Then each read returns the current sensor and increments the sensor number internally in the slave, so the next read will get the next sensor.

That way you have a way to "reset" the sensor index that you are reading from, and it's reasonably quick to get all the sensors, since you just need to do multiple reads after a single write.


How to get weight data from glass electronic bathroom scale sensors? I am doing a small project with a bathroom scale but I run into some problems. I am using an Arduino Uno V3, HX711 module amp and a scale.

Scale:

HX711 amplifier:

I disassembled the scale to get to sensor wires and I am a bit confused. These sensors have three wires each. So they are half bridge sensors. The scale is using 4 sensors so when the scale is measuring it is measuring with a full bridge. And these 3 wires are RED, BLACK, BLUE. I don't know what is black (GND or Positive) and blue (same guess). Four red wires are given names E+, E-, S+ and S-. I will provide a picture of the disassembled scale.

Two blue wires are soldered together on each side. I guess red wires are signal (S+, S-, E+ and E-) but what are Blue and Black? Then I soldered the wires to these wires to get sensor readings but I don't know what is what.

The sensor is looking like this:

I tried:

Two different libraries for this project both named HX711 (for this module)
Changing A+ for A- on module

// Hx711.DOUT - pin #A1
// Hx711.SCK - pin #A0

#include "hx711.h"

Hx711 scale(A1, A0);

void setup() {

  Serial.begin(9600);

}

void loop() {

  Serial.print(scale.getGram(), 1);
  Serial.println(" g");

  delay(200);
}

with no success. I get 0.0g on the serial monitor when calm, and the same when load is on.

My questions are:
How to know which wire is GND, +5V and which is signal? How to connect 4 of these sensors to read data? How to use HX711 libraries available and HX711 module? And, most important, how to read data from this scale on serial?

Your four half bridge load cell sensors can connect into a full wheatstone bridge as in https://electronics.stackexchange.com/a/199470/30711

If your sensors are like this 50kg load cell from SparkFun's https://www.sparkfun.com/products/10245  or Ebay's http://www.ebay.com/itm/4pcs-Body-Load-Scale-Weighing-Sensor-Resistance-Strain-Half-bridge-Sensors-50kg-/251873576571 they might have a compression and tension gage both on the top surface. The Ebay site has a diagram like:

... which indicates a positive strain gauge on the red-white, and a negative strain on the red-black. (note that the coloring order in this diagram does not match the coloring order in this picture.  I have a similar gauge with blue-red-black colors, and the positive strain gauge is the right pair, negative on the left.) The gauged surface on the center bar between the face-to-face coupled 'E's in the sensor should act like a parallel bar and has portions under compression and under tension, rather than purely under tension.  In cross-section, the gauged bar in the center is sort of the cross-piece in a Z-shaped spring. In this case, the strains oppose each other, and, if manufactured well, the reduction of resistance in the negative strain portion will offset the increase in resistance in the positive strain portion and the total white-black resistance should be constant.  One still needs to set up the bridge so that the voltage dividers move in opposite directions with added load, and 4 devices wired in a white-to-white and black-to-black loop should work as above.

If you wire four of these up carefully by flipping them around so the stress sensitive portions unbalance the bridge constructively, you can use all four sensors without any extra resistors.

Basically, two diagonally-opposite sides of a wheatstone bridge are each formed by the compression elements of two gauges wired in series, while the remaining two sides of the bridge are each formed from two tension elements from two cells.  With load on all the sensors, the compression resistances are reduced, while the tension resistances are increased and it pulls the bridge out of balance.

To get this, wire all four sensors in a big ring with maximum resistance, matching colors and initially ignoring the red center tap wires.  (This is the function of the soldered-together blues and blacks are in your scale.)  Choose two opposite (red) center taps as E+ and E-, and the remaining two (red) center taps as S+,S-.  Put the excitation voltage on the E+/E- from the diagram above and read a force-sensitive voltage difference across S+/S-, and this is what you feed into your HX711 as A+ and A-  (Ignore B+/B- as a second, unused channel.)

Here's a schematic with gauges 1-4 as G1 G2, G3, G4 per the above specs, applying an excitation on the G1 and G3 reds, and reading the signals off the G2 and G4 reds.  The G4 gauge is loaded a bit with some positive strain increasing the G4+ resistance, and some negative strain reducing the G4- resistance.  Ideally, loading G4 with 25kg would produce 0.5mV/V times its 2.5V excitation voltage, producing 1.250mV across Sig+/Sig-, and stretching R8 to be 1001 ohms and compressing R7 to 999 ohms as shown.   (The schematic/simulator thing on electronics.stackexchange.com is pretty cool.)

simulate this circuit – Schematic created using CircuitLab

Instead of the "White" wires in the diagram and like on my gauges, consider it the "blue" wires from your scale's sensors.

With only two of these half-bridge sensors, one should not match the end colors and hook white-to-black (blue-to-black) and black-to white, (black-to-blue) imposing an excitation voltage from between these two junctions, and read the differences across the reds, as increased load pulls one side high and the other side low.  This will look like the plain 4-resistor wheatstone bridges in the common datasheets, rather than the 4-half-bridge/eight-resistor scheme above.


Load Adafruit GFX bitmap fonts on desktop for pixel-level design I am designing UI for 160x128 ST7735-based TFT display which will be displayed using Adafruit's GFX library (and the driver in Adafruit_ST7735.h). I am using the default bitmap font (custom fonts don't provide the white-out functionality, causing flicker) and would like to load it in some desktop pixel editor (like Gimp or some pixel-art editor) so that I can work the design out on desktop.

There are many posts about converting regular (TFT, OTF) fonts to the c-style array, I need to do the opposite. If possible, including the scaled variants, so that I have 1:1 corespondence :)

Any tips on this?

As explained here and here the font format in the GFX-library is GFXglyph, you can use the free tool from the second link adafonteditor v1.0.3 on the desktop.EDITOk so its actually decompile the gfx header file to something on the desktop. Take a look at the Adafruit GFX Font Customiser Source can be used as basis for own projects or compiled to the designated OS.


Arduino Control TV over RS232 I have a LG TV(LG 32SL800 ZB), which has a RS232-Port for Control and Service.

And I am wondering if I could control this port with my Arduino (NODE-MCU) and a module like this one RS232 Board?

How could I then control the TV? This is the Manual for the TV at page 124 there are the commands how to control it, but how can I send them?

My last question is, how long can the cables from the arduino to the module be? They have to be about 2-3m long! Is that possible without any other hardware?

And I am wondering if I could control this port with my Arduino (NODE-MCU) and a module like this one?

Yes, you can, though choose a board based around the MAX3232 for a 3.3V MCU board.

  How could I then control the TV? This is the Manuel for the TV at page 124 there are the commands how to control it, but how can I send them?

Exactly as they show in the manual. For example:

Serial.print("ka 0 01\r");

That would turn on every TV connected to the serial bus.

  My last question is, how long can the cables from the arduino to the module be? They have to be about 2-3m long! Is that possible without any other hardware?

You can get away with no more than maybe 1 meter between the Arduino and the RS232 board. Keep that as short as possible. However between the RS232 board and the TV you can have up to 15 meters of cable.


connecting a small motor to arduino using a transistor I want to connect a small motor (water pump) to an arduino, and I am not sure about the circuit.
The pump is small, works with 3.3V, but consumes 0.1A so I decided to use a transistor. The one I have is BF547, an NPN type small transistor. It supports currents up to 100 mA.
I measured the hfe (beta) of the transistor, and it is 370. The Vcc is 3.3V, and the current through the motor is 0.1 A, therefore:
A. the Ib equals to Ic/hfe = 0.1A/370 giving Ib = 0,00027A
B. with the Vb at 3.3V(pin voltage) and Vbe at 0.7 (datasheet) the Rb = (Vb-Vbe)/Ib = 9558 Ohm (10kOhm)
My questions are:

Did I calculate the base resistance correctly?
Do I need any additional resistor for the collector, next to the pump? Is it possible that more current flows through the collector-emitter?
According to the datasheet of BF457 100mA is the max Ic it can take. Should I limit the pump by adding a small (10 Ohm) resistor to it (33 Ohm[motors resitance] + 10 Ohm for 3.3 V gives a current of 76 mA)

I am attaching the schematics (linear voltage regulator is there only to stabilise the Vcc provided by an old dc power source I found)
Thanks a lot for any suggestions!

I like your thought process (even though it might not be completely correct), I've seen how little thought were put in for such simple circuit design in the Arduino community, including from some Youtuber celebrities who teaching Arduino and claims to have an EE degree.
BF547 is an RF amplifier transistor, not for switching application, it would be better to use an NPN transistor such as 2N3904 which is designed for switching application and has a Ice of 200mA.
Your resistor value is too high. If your motor is designed to operate at 100mA 3.3v condition, you would want your driver to provide AT LEAST that current. Assuming your are driving the transistor with 5V out from an Arduino, a 1k bias resistor would limited the Ibe to (5 - 0.7Vbe)/1000=4.3mA, take a very conservative DC current gain of 30 (it typically in the range of 30 - 80 for switching transistor, and hfe could be in the range of 100 - 300 when frequency go up, but this will not be the case for Arduino even you drive the motor using PWM), which will capable to deliver Ice of 4.3 x 30 = 129mA. This should meet your Motor requirements.
You would need a protection diode connected between 3.3V and collector with its cathode connect to 3.3V and its anode connect to the collector of the transistor. An 1N4148 (max If=200mA) would be okay for this specific motor, or even better, use any Schottky diode with current and voltage limit higher than your application).