Arduino Nano and WS2812 I am new to electronics and especially Arduino-based products. I am currently trying my hand at using 5 segments of WS2812 RGB LEDs and using a Nano to control them. I included the picture below for the pin numbers.

If I wanted to run 5 groups of LEDs and use a library like the Adafruit Neopixel or Fastled to control the leds, what would be the best way of wiring them up to the Nano?

I am under the impression that the positives should all be connected to pin 27, the 5v pin, with a 1000 µF 25V capacitor. The ground wires will all be connected together to pin 04, Ground. The data pins will be wired to pins 6, 8, 9, 12 and 13 and each will have a 470 ohm 1/2W resistor on each pin.

I am unsure whether any of the other pins can be used for data pins. The input voltage will vary since this is used on a multi-rotor that I am building. The battery voltage will vary from 12.6V all the way down to maybe 9 volts. I was thinking of using a step down adjusted to 12V to keep the voltage at or under 12v and that will be connected to pin 30. I would love to hear if there are any better ways of wiring this project up.

Also would it be a better idea to power the LEDs from a 5V dedicated source and just use the Nano for the data pin connection? I will only be using roughly 30-40 WS2812s.

Regarding “The data pins will be wired to pins 6, 8, 9, 12 and 13 and each will have a 470 ohm 1/2W resistor on each pin”, note that WS2812s typically are connected together in strings, with the DO (data out) pin of each upstream unit connected to the DI (data in) pin of the next unit downstream. Thus, there is no need to allocate five Arduino IO pins; one is enough.

For further background on WS2812 mechanisms, see for example Is it possible to infer the length of a neopixel string using 1-wire protocol?, and see discussions and diagrams at adafruit.com and sparkfun.com.

Regarding use of an efficient step-down switching-supply voltage regulator set for 12 V out, if you use an adjustable regulator you might as well set it lower than that, for example at 8 or 9 volts. Typically, the regulators on Arduino boards that convert Vin to +5 or +3.3 V are linear regulators rather than switching regulators, so every unnecessary extra volt (above the dropout limit) proportionally increases the amount of wasted energy.

In typical use, a WS2812 draws 20 to 60 mA current, supposing up-to-five-volt power. Thus, a string of 30 to 40 of them will draw at least 0.6 A, in most cases, and up to 2.4 A, if all are on at top brightness. In either case, an external power supply would be de rigueur. You would connect the external supply's ground to the Nano's ground; the +5Vs need not be connected together.

Edit: Addressing questions from comments

Re “if one data in will control the entire array of LEDs, it should be connected to D13”, I'm not aware of any reason for that idea, and indeed would recommend against it. On many Arduino models, D13 drives an LED. While the Uno uses a buffer amplifier to drive the LED, the Nano just has a 680 Ω resistor in series with an LED. I'd not load it further.

Wiring each of several strips in its own chain seems quite reasonable. Yes, you could wire all the DIs of 30 or 40 WS2812 units in parallel. However, parallel inputs would require 30 or 40 wire runs, vs. the simple wiring chain the WS2812 is intended for. Note, per its spec sheet the WS2812 DI load is ±1 µA max, so one '328 IO pin could drive hundreds of them. But input capacitance, up to 15 pF each, probably precludes driving thousands in parallel.

If performance is an issue, possibly use short chains (up to several dozen units long) in parallel, rather than one long chain of hundreds of units. The spec sheet says, “When the refresh rate is 30fps, low speed model cascade number are not less than 512 points, high speed mode not less than 1024 points.” (Low speed refers to 400Kbps signalling; high speed, 800Kbps).

Note, paralleled chains improve refresh rates only when multiple chains are used to show the same pattern. Otherwise, each chain being refreshed separately is no faster than refreshing the same number of units in series. The library that drives a chain of WS2812s hogs the whole processor each time it sends a chain of data. Also note that scan rates of 400 Hz are mentioned in the spec sheet. It is likely to be futile to try to exceed that by paralleling units.

Summary: If you have a dozen or so units on a rotor arm, I'd wire them in series. If it's more convenient to keep each arm's wiring separate from that of other arms, then do so. If each arm will show the same pattern as other arms, you could wire the chain inputs (the first units in each chain) in parallel, else would use separate driver pins.


How to extend my Sketch for Multiple Inputs and Outputs I am using  4 Push Buttons and 4 leds in my project. Here the sketch is only for one push button and one Led. I want extend my sketch upto 4 push buttons and 4 leds .Please tell what changes I make in my sketch. Please any body can make changes in my sketch.
here is sketch:

const int buttonPin =2;    // the number of the pushbutton pin
const int ledPin = 13;      // the number of the LED pin

// Variables will change:
int ledState = HIGH;         // the current state of the output pin
int buttonState;             // the current reading from the input pin
int lastButtonState = LOW;   // the previous reading from the input pin
long lastDebounceTime = 0;  // the last time the output pin was toggled
long debounceDelay = 50;

void setup() {
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, ledState);
}

void loop() {
  int reading = digitalRead(buttonPin);
  if (reading != lastButtonState) {
    // reset the debouncing timer
    lastDebounceTime = millis();
  }

  if ((millis() - lastDebounceTime) > debounceDelay) {
    // whatever the reading is at, it's been there for longer
    // than the debounce delay, so take it as the actual current state:

    // if the button state has changed:
    if (reading != buttonState) {
      buttonState = reading;

      // only toggle the LED if the new button state is HIGH
      if (buttonState == HIGH) {
        ledState = !ledState;
      }
    }
  }

  // set the LED:
  digitalWrite(ledPin, ledState);
  lastButtonState = reading;
}

I'll show you the long but simple way. Just follow this logic in your setup and loop and you'll be ok. If you still don't understand and want more, tell me and I'll add more code for you.

Do something like this:

const int buttonPin1 = 2;    // the pin the button is connected to
const int buttonPin2 = 3;
const int buttonPin3 = 4;
const int buttonPin4 = 5;

const int ledPin = 6;        // the pin the led is connected to
const int ledPin = 7;
const int ledPin = 8;
const int ledPin = 9;

int ledState1 = HIGH;         // the current state of the output pin
int buttonState1;             // the current reading from the input pin
int lastButtonState1 = LOW;   // the previous reading from the input pin
long lastDebounceTime1 = 0;  // the last time the output pin was toggled
long debounceDelay1 = 50;

int ledState2 = HIGH;         // the current state of the output pin
int buttonState2;             // the current reading from the input pin
int lastButtonState2 = LOW;   // the previous reading from the input pin
long lastDebounceTime2 = 0;  // the last time the output pin was toggled
long debounceDelay2 = 50;

int ledState3 = HIGH;         // the current state of the output pin
int buttonState3;             // the current reading from the input pin
int lastButtonState3 = LOW;   // the previous reading from the input pin
long lastDebounceTime3 = 0;  // the last time the output pin was toggled
long debounceDelay3 = 50;

int ledState4 = HIGH;         // the current state of the output pin
int buttonState4;             // the current reading from the input pin
int lastButtonState4 = LOW;   // the previous reading from the input pin
long lastDebounceTime4 = 0;  // the last time the output pin was toggled
long debounceDelay4 = 50;


Faster way to parse a HTTP response in Arduino I send a GET http request to a server and get following data back.

HTTP/1.1 200
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Fri, 16 Nov 2018 16:30:05 GMT
Connection: close

35
{
  "uuid" : "13b29524-7e12-48fb-bbf9-4396aefff45d"
}
0

with the following code I get the header info and the body.

void parseResponse() {
  boolean headerEnd = false;
  byte lineCount = 0;
  String line;
  char endOfLine[] = "\r\n";
  while (1) {
    if (client.available()) {
      char inChar = client.read();
      if (!headerEnd && line.endsWith(endOfLine)) {
        // Just save the first then headers
        if (lineCount == 10) {
          headerEnd = true;
        } else {
          headers[lineCount] = line;
          line = "";
          lineCount++;
        }
      }

      if (line.endsWith("close")) {
        line = "";
        headerEnd = true;
      }

      if (headerEnd && line.endsWith("}")) {
        line.toCharArray(response, sizeof(response));
        client.stop();
        break;
      }

      line += inChar;
    }
  }
}

this thakes 60 - 70ms to parse. Is there a faster way to parse? I think that's slow, for so little text, in the world of AVRs.

there are nice functions inherited from Stream class

int parseResponse(char uuid[], int size) {
  if (!client.find("HTTP/1.1")) // skip HTTP/1.1
    return -1;
  int st = client.parseInt(); // parse status code
  int l = -1;
  if (st == 200 && client.find("\"uuid\" : \"")) {
    int l = client.readBytesUntil('"', uuid, size);
    uuid[l] = 0; // terminate the C string
  }
  return l;
}


How to improve date-time control from RTC? I want to run cameras at a remote site from external batteries as long as possible. I need power-miser Arduino to switch battery power on/off at set intervals (e.g. 5 min) during daytime only. I am a beginner with Arduino and electronics.

Have set up 'breadboard' arduino with mosfet module for switching the power supply and RTC module, both from Freetronics (http://www.freetronics.com.au/collections/modules/products/real-time-clock-rtc-module#.V-i-S8knuPs). Following their recommendation I'm using RTC library here: http://rweather.github.io/arduinolibs/index.html

I need to refine the crude hour-based script below. Weatherley library returns separate objects e.g date.day, time.hour etc. Is there a simple way to convert to date-time object? Then calculate sunrise and sunset times based on latitude?

  #include <JeeLib.h> //  power saving library
  ISR(WDT_vect) { Sleepy::watchdogEvent(); } // Setup jeelip watchdog
  #include <SoftI2C.h> // rweather lib for RTC module
  #include <DS3232RTC.h> //rweather lib for RTC module
  SoftI2C i2c(A4, A5); // assign pins to SDA and SCL
  DS3232RTC rtc(i2c);
  RTCTime time;
  int gatePin = 12;   //  mosfet Gate connected to digital pin
  int startHour = 6; // want to replace with sunrise time
  int endHour = 19; // want to replace with sunset time

void setup()
{
 pinMode(gatePin, OUTPUT);   //  output pin for mosfet module
}

void loop()
{ // main loop starts here
  rtc.readTime(&time);  //get current time
  if (time.hour >= startHour && time.hour < endHour) // check daytime
  {   // if condition begins here
      while(time.hour < endHour ) // daytime operating period

      {   //  while loop (day) begins here
      digitalWrite(gatePin, HIGH);   // turn on gate for power supply
      Serial.flush(); //needed before sleepy
      Sleepy::loseSomeTime(30000); // low power wait
      digitalWrite(gatePin, LOW);    // turn off gate for power supply
      Serial.flush(); // needed before sleepy
      for (int i=0; i <= 3; i++){
        Sleepy::loseSomeTime(65000); // low power wait
        } // end for loop
      rtc.readTime(&time);
      } // end while loop (day)
      } //  if condition (daytime) ends here
else
  { // else condition (night time) starts here
    while (time.hour >= endHour || time.hour < startHour )
    { // while loop (night) begins here
    for (int i=0; i <= 59; i++){
    Serial.flush(); // needed before sleepy
    Sleepy::loseSomeTime(65000); // low power wait
    } // end for loop
    rtc.readTime(&time);
    } // while loop (night) ends here
// need to refine timing else hour-long wait periods can run past the end of night period
  } // else condition (night) ends here
} //  main loop ends here

I will be very grateful for advice, many thanks in advance!

EDIT: Part of my original question could be answered - see below about time-date format without using RTC. Issues with RTC appear harder than I expected. I think they will need a new question later.

Is there a simple way to convert to date-time object?

Not with this library. But you can find other
libraries supporting the DS3232 which work with the Arduino
Time library[]. This time library provides both the date and time in a
single object, either:

a time_t, which is just the number of seconds elapsed since a
standard “epoch”
a tmElements_t struct, which has the date and time broken into
separate elements (year, month, day, hour...).

  Then calculate sunrise and sunset times based on latitude?

There are quite a few algorithms describes on the Web for that. The more
accurate ones are also the more complex.

  #include <SoftI2C.h>

Doesn't your Arduino have a hardware I2C port? That would be more
efficient than software emulation.

  Serial.flush(); //needed before sleepy

It's only needed if you are actually using the serial port.

Edit: I saw on your other question that you have been bitten by
an incompatibility between the Arduino Time library and the file
time.h from avr-libc. Now I just noticed that avr-libc includes the
functions sun_rise() and sun_set() that you may find
handy. Not sure they will play well with the Arduino time libraries
though. One possible incompatibility is the fact that they use different
epochs for defining time_t (year 1970 v.s. 2000).


MatLab connection to Arduino using Bluetooth I am attempting to send some information from MatLab to an Arduino Uno via Bluetooth with the following

MatLab program:

b=Bluetooth('HC-06',1);
fopen(b);
for i=1:1:15
  fprintf(b,i);
  out(i) = fscanf(b,'%d');
end
fclose(b)

and Arduino program

int matlabval=0;

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

void loop() {
  if (Serial.available() > 0) {
    matlabval = Serial.read();
    Serial.println(matlabval);
  }
}

the output  of arduino is

1
10
2
10
3
10
4
10
5
10
6
10
7
10
8
10
9
10
10
10
11
10
12
10
13
10
14
10
15
10

The number 10 appears after each number. Why is that so?

Thanks in advance!

As discussed in the comments, the "problem" seemed to be Matlab adding a "New Line" which is a decimal 10 in ASCII.

  asciitable.com Decimal 10 is the ASCII code for a "New Line" so it appears your Matlab send code will add a "New-line" after each sent value. – Paul Apr 14 at 8:15

    thank you very match the problem is solved – abbas hussien 5 hours ago

You might want to accept this answer so that this question gets "closed" and the site's statistics will be more accurate.
It will also avoid this question being bumped up by the system and people reading into something that has already been solved.


Can't compile my library because "String does not name a type" I am writing a small library to move some code out of the arduino sketch and make it reusable. Problem is that it does not compile since "String does not name a type".
This is my code (reduced):
myESP.h:
#ifndef MYESP_H
#define MYESP_H

#include "Arduino.h"

#include <String>

#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <WiFiClient.h>
#include <WiFiClientSecure.h>
#include <WiFiServer.h>
#include <WiFiUdp.h>

class myESP {
    private:
        const char* _ssid;
        const char* _password;
        const char* _host;
    public:
        myESP();
        myESP(char * ssid, char * pwd, char * host);
        String macToStr(const uint8_t* mac);
        String doGet(String data, String sensor, int duration);
};
#endif

myESP.cpp:
#include <String>

#include "Arduino.h"
#include "myESP.h"

myESP::myESP() {}

myESP::myESP(char * ssid, char * pwd, char * host) {
    _host = host;
    _password = pwd;
    _ssid = ssid;
}

myESP::String macToStr(const uint8_t* mac) {
}

myESP::String doGet(String data, String sensor, int duration) {

}

When i try to compile it, I get the following:

/Users/lbedogni/Documents/Arduino/libraries/myESP/myESP.cpp:14:1:
error: 'String' in 'class myESP' does not name a type  myESP::String
macToStr(const uint8_t* mac) {
/Users/lbedogni/Documents/Arduino/libraries/myESP/myESP.cpp:22:1:
error: 'String' in 'class myESP' does not name a type  myESP::String
doGet(String data, String sensor, int duration) {

I have tried to change the order of the imports, change libraries, but still it does not compile.
Any idea?

Your syntax is wrong in myESP.cpp. Change this:

myESP::String macToStr(const uint8_t* mac) {
}

myESP::String doGet(String data, String sensor, int duration) {

}

to this:

String myESP::macToStr(const uint8_t* mac) {
}

String myESP::doGet(String data, String sensor, int duration) {

}

The return type is String and the function implementation should be prefixed with the class name myESP::. Obviously, you also need to fill in the body of the implementation or you'll get more errors because you don't actually return anything.


Don't understand problem with my code I'm trying to get a robot car(elegoo one) to do the obstacle avoidance course. I am trying to write my own one from scratch to better myself and thus would really appreciate it if someone were to tell me what's wrong with my code and why it's not working
#include <Servo.h>  //servo library
Servo myservo;      // create servo object to control servo
Servo servosweep;
int Echo = A4;
int Trig = A5;

#define ENA 5
#define ENB 6
#define IN1 7
#define IN2 8
#define IN3 9
#define IN4 11
#define carSpeedForward 100
#define carSpeedLeftandRight 150
int rightDistance = 0, leftDistance = 0, middleDistance = 0;
int pos=0;

void forward(){
  analogWrite(ENA, carSpeedForward);
  analogWrite(ENB, carSpeedForward);
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, HIGH);
  Serial.println("Forward");
}

void back() {
  analogWrite(ENA, carSpeedForward);
  analogWrite(ENB, carSpeedForward);
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, HIGH);
  digitalWrite(IN3, HIGH);
  digitalWrite(IN4, LOW);
  Serial.println("Back");
}

void left() {
  analogWrite(ENA, carSpeedLeftandRight);
  analogWrite(ENB, carSpeedLeftandRight);
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, HIGH);
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, HIGH);
  Serial.println("Left");
}

void right() {
  analogWrite(ENA, carSpeedLeftandRight);
  analogWrite(ENB, carSpeedLeftandRight);
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);
  digitalWrite(IN3, HIGH);
  digitalWrite(IN4, LOW);
  Serial.println("Right");
}

void stop() {
  digitalWrite(ENA, LOW);
  digitalWrite(ENB, LOW);
  Serial.println("Stop!");
}

//Ultrasonic distance measurement Sub function
int Distance_test() {
  digitalWrite(Trig, LOW);
  delayMicroseconds(2);
  digitalWrite(Trig, HIGH);
  delayMicroseconds(20);
  digitalWrite(Trig, LOW);
  float Fdistance = pulseIn(Echo, HIGH);
  Fdistance= Fdistance / 58;
  return (int)Fdistance;
}

void setup() {
  myservo.write(pos);
  myservo.attach(3);  // attach servo on pin 3 to servo object
  Serial.begin(9600);
  pinMode(Echo, INPUT);
  pinMode(Trig, OUTPUT);
  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
  pinMode(IN3, OUTPUT);
  pinMode(IN4, OUTPUT);
  pinMode(ENA, OUTPUT);
  pinMode(ENB, OUTPUT);
  //stop();
}

void loop(){
  for (pos = 0; pos < 90; pos += 1.0) {
  servosweep.write(pos);
  delay(50);
  leftDistance=Distance_test();
  }

  myservo.write(90);
  middleDistance=Distance_test();

  for (pos=90;pos<=180;pos+=1.0){
    servosweep.write(pos);
    delay(50);
    rightDistance=Distance_test();

  }

  if(rightDistance > leftDistance) {
        right();
        delay(360);
      }
      else if(rightDistance < leftDistance) {
        left();
        delay(360);
      }
      else if((rightDistance <= 40) || (leftDistance <= 40)) {
        back();
        delay(180);
      }
      else {
        forward();
      }
}

I'm trying to get the ultrasonic sensor to read values from the left(0 to 90), the middle(90) and the right(90 to 180) and then use them for comparison to decide where to go. When I run this code my car goes in circles and I don't know what the problem is. Any help would be appreciated.

As jsotola writes, you are running through the 0-89 position and updating leftDistance every time. Then you find the middleDistance and finally you go through 91-180 and update rightDistance. After the two for loops, leftDistance will have the value for 89 and rightDistance will have the value for 180 because you overwrite your value without doing anything with it.
Start by skipping the for loops and measure at 0, 90 and 180 and use these values as you left, middle and right distance. When deciding if you want to back up, use the middle distance. Remember to use a delay between measurements that is large enough for the servo to get to the position for the next measurement


measure +3V and -3V through resistor divider and switch on/off by digital pins I've seen that resistor dividers can be used to read negative voltages, but I'ld like if there is a way to accomplish this with less components and having a way to turn this off.

I was thinking if there would be an extreme option of changing from pinMode INPUT to INPUT_PULLUP or INPUT_PULLDOWN to power the circuit and use the 20k pullups to make part of the divider, together with another resistances on the input. Alternatively, switching from INPUT to OUTPUT would be fine.

What I want to measure is an external +3V/GND/-3V power supply (battery pack) that shares the GND with the arduino SAMD21 (3.3V), measuring both +3V and -3V, and avoiding drain when not measuring (hence the pin mode changes)

Currently I'm using this schema to measure the voltage of +5V supply battery (connected through VIN, thus using the internal regulator), by dividing with 2 1Mohm resistances, ground to digital pin and measurement by internal adc. I don't need so much precision, so this is enough here. So I'm looking for the same or better alternatives, but for the -3V I don't know how to properly calculate the 3 resistor divider.

When measuring a voltage that is higher than the maximum rating, the voltage of interest is tied to ground with a voltage divider. When measuring a negative voltage, you instead have to tie the voltage of interest to the positive supply voltage (study the answers to this question).

In theory you can use the internal pullup to spare one resistor, but I would consider this a bad practice and recommend using an external pullup for the following reasons:

a uC's internal pullups/-downs are not accurate and sometimes not specified
especially when measuring negative voltage, chances are that harmful voltage is applied to the adc (consider the default state of a gpio)
a pullup/-down is an uncritical component concerning its value and precision. Therefore they are very cheap


Is it possible to create an interface between Teensy 3.2 and a DSP? I realize that this is a forum for Arduino but since the Teensy 3.2 is compatible with the Arduino IDE I thought it would be appropriate to ask the question here.

Anyway, can I create an interface between the Teensy 3.2 and a DSP, more specifically the TMS320C5534-Fixed-Point Digital Signal Processor and how could I go about it?

What I am trying to do do is capture an EEG and EoG (electrooculogram) signal, amplify it, filter the signal, use the DSP for ADC and signal processing and finally get this information from the DSP to the Teensy 3.2, which will then make a decision based on the signal obtained from the DSP.

Maybe this is a simple question but I couldn't find any answers online. I am pretty new to the world of microcontrollers.

Thank you guys!

I would use one of the serial interfaces and connect them together that way.  If Asyinc run as fast as reliable.


MIDI output circuit behaving incorrectly when not connecting with USB I recreated this circuit to send MIDI notes to my MIDI-USB adapter to my computer.

It works fine when the Arduino is powered via USB. When I power the Arduino Nano with 9v on Vin however, the output is gibberish. It just spams the input monitor on my computer with random midi commands. For testing I used this code:

    #include <MIDI.h>

    MIDI_CREATE_DEFAULT_INSTANCE();

    static const unsigned ledPin = 13;
    bool on = false;
    void setup()
    {
        pinMode(ledPin, OUTPUT);
        MIDI.begin(MIDI_CHANNEL_OFF);
    }

    void loop()
    {
        digitalWrite(ledPin, on);
        on = !on;
        MIDI.sendControlChange(12, 127, 1);
        delay(1000);
    }

The Arduino itself seems to be working fine when powered with 9v (note that I tested with both a wall power supply as well as a 9v battery) as the TX-led still  flashes briefly and the built-in led also toggles nicely.

At first I blamed my power supply and/or my power supply, but both work fine on my MIDI-keyboard so I don't think they are to blame.

Worth mentioning: When the Arduino was powered by Vin, I also as a test plugged in the USB-cable in the Arduino, But only touched the connector on the USB-port on my computer. I then received the correct notes.

Because of this I think it is an issue with the grounding. What am I doing wrong?

EDIT: Thanks for the response guys. I think I diagnosed my problem incorrectly. I'm using a cheap Chinese MIDI-adapter which I pried open, and it lacks an optocoupler. I'm getting a decent MIDI adapter now. Thanks!

If you are connecting multiple devices then they have to share a common ground.

I only know about British mains sockets, they all have an earth pin connecting to a common ground, so usually you are OK.

Plug in transformers 'wall warts' sometimes don't connect to ground, the give away is the plastic pin.  In this case you need to provides a separate earth and connect it to the rest of the equipment.

PCs normally have a good earth and this is passed by the USB to connected devices.  So "the Arduino always works when it is connected to the PC" is usually a good indicator of an earthing issue.

I think your keyboard uses a wall wart and therefore when you remove the USB they both float.  Touching the USB lead to the Arduinos USB socket grounds it all again.

So it looks like you diagnosed the fault correctly :)


How to do a software reset on MAX7456? I messed around with the MAX7456 chip for a while, even the character set updating sketch seemed to work after a few modifications. But now it is not displaying anything with the Hello World sketch that worked before. No signal seems to pass through it, the screen is just black.

The datasheet says that one must write Video Mode 0 Register (VM0) at address 00H bit 1 to 1 via SPI to reset it, how would I do it? Also, how would one verify that the chip indeed did reset itself and responds to the commands given to it afterwards? (The board looks like this)

The datasheet says:

  The SPI commands are 16 bits long with the 8 most significant bits (MSBs) representing the register address and the 8 least significant bits (LSBs) representing the data ...

Thus, you need to write address / data after selecting the chip.

digitalWrite (SS, LOW);  // select the chip
SPI.transfer (0x00);     // select address 0x00 (Video Mode 0)
SPI.transfer (bit (1));  // write bit 1 (Software Reset Bit)
digitalWrite (SS, HIGH); // done

According to the datasheet you need to wait around 20 µs for the operation to complete. You could, of course, just wait 20 µs but it might be nice to see if the bit gets cleared.

  byte result;

  do
    {
    digitalWrite (SS, LOW);      // select the chip
    SPI.transfer (0x80);         // select address 0x00 (Video Mode 0) - read mode
    result = SPI.transfer (0);   // read it
    digitalWrite (SS, HIGH);     // done
    } while (result & bit (1));  // loop while not reset yet

  Also, how would one verify that the chip indeed did reset itself and responds to the commands given to it afterwards?

I'm not sure, without the chip in hand, what other tests you can make, but if you added a counter into the above loop, you could probably verify that it was doing something. eg.

  // reset chip
  digitalWrite (SS, LOW);  // select the chip
  SPI.transfer (0x00);     // select address 0x00 (Video Mode 0) - write mode
  SPI.transfer (bit (1));  // write bit 1 (Software Reset Bit)
  digitalWrite (SS, HIGH); // done

  byte result;
  unsigned int counter = 0;

  // wait for it to become ready, or time-out
  do
    {
    digitalWrite (SS, LOW);      // select the chip
    SPI.transfer (0x80);         // select address 0x00 (Video Mode 0) - read mode
    result = SPI.transfer (0);   // read it
    digitalWrite (SS, HIGH);     // done
    if ((result & bit (1)) == 0)
      counter++;     // count times not ready
    } while ((result & bit (1)) && (counter < 1000) );  // loop while not reset yet

  if (counter == 0 || counter >= 1000)
    {
    // chip does not seem to be responding
    }
  else
    {
    // all OK!
    }


How to select hardware for my Arduino board? As I embark on my first Arduino project, I have lots of questions. Specifically, what considerations should I make when selecting equipment, and what are the critical parameters to safe operation?

Some elaboration upon my questions can be seen below. However, outlining general principals of equipment selection would be highly useful.

I have an Arduino Uno. The Uno has an input voltage of 6-20 V, and operating voltage of 5 V as from the tech specs. Does this mean that I can select any sensor with less than 20 V output to send data to my Arduino?

I am interested in using a sensor like this
 Texas Instruments HDC1080 High Accuracy Digital
Humidity Sensor, which has a supply of 5.5 V. If my logic is correct, this output should be fine. I should know whether or not I need to buy some sort of shield based purely upon the output pins of the sensor, correct? I know I have 6 analog and 6 PWM/digital pins on the Arduino, so the digital signal should be capable of being processed by my Arduino. However, the interface type on the sensor product is I2C, but I am unsure as to what this means or if it needs to be a consideration.

For your first project, power the Arduino Uno with the USB cable and use everything at 5V.
There are tutorials which guide you step-by-step to make something. The Adafruit tutorials are very good.

The HDC1080 is a sensor that works at 3.3V and at 5V. That means you can use it with the 5V Arduino Uno without problem.
This Tindie HDC1080 module points to a HDC1080 library on Github. I suggest you try to make that work.

If you can not get data out of the sensor, then you should start with something very simple. A few leds (with series resistors) or a LDR light sensor is fun to start with.

As soon as you start using higher voltages (for example 12V) you might consider buying a spare Arduino Uno, because the Arduino Uno will be blown when 12V touches one of the pins.

Be also careful with sensors that can only handle 3.3V and not 5V. Since the Arduino Uno runs at 5V, a pin of the Arduino could feed 5V into the sensor and damaging the 3.3V sensor.


Water heater coding problem I need help with my coding. I'm still learning on how to use interval millis().

Currently I'm working on a water heater with a safety feature. This means that you can only pour water out when you activate the child-lock feature. The child-lock feature will turn on for 5 seconds and within that 5 seconds if you pour the water out, the timer will pause until you finish pouring your water and the 5 second timer will start again and the system goes off after that.

If the child lock feature on for 5 second without any action, it will turn off the system again. My lecturer does not allow me to use the delay() function so I already did my coding using millis().

This is my code so far:

const int redLed = 2;
const int greenLed = 3;
const int yellowLed = 4;
const int greenbigLed = 7;

const int buttonPin1 = 5;
const int buttonPin2 = 6;

int buttonState1 = 0;
int buttonState2 = 0;
float tempC ;
int analogPin = A0;
int yellowLedState = 0;

const long interval1 =0;
const long interval2 = 5000;
unsigned long previousMillis = 0;

void setup() {
  // put your setup code here, to run once:
pinMode(2,OUTPUT);
pinMode(3,OUTPUT);
pinMode(4,OUTPUT);
pinMode(5,INPUT);
pinMode(6,INPUT);
Serial.begin(9600);
digitalWrite(yellowLed,yellowLedState);

}

void loop() {
  // put your main code here, to run repeatedly:
int analogValue = analogRead(analogPin);
int buttonState1 = digitalRead(buttonPin1);
int buttonState2 = digitalRead(buttonPin2);
int yellowLedState = digitalRead(yellowLed);
tempC = analogValue / 10 ;
Serial.println(tempC);
unsigned long currentMillis = millis();
unsigned long currentMillis2 = millis();

if (tempC <= 89.9 && tempC >= 0){
  digitalWrite(redLed,HIGH);
  digitalWrite(greenLed,LOW);
}else if(tempC == 102){
  digitalWrite(redLed,LOW);
  digitalWrite(greenLed,HIGH);
}

if(currentMillis - previousMillis >= interval2){
  previousMillis = currentMillis;
  if(buttonState1 == HIGH){
   // if(currentMillis2 - previousMillis2 >=interval2){
     if (yellowLedState == LOW) {
          yellowLedState = HIGH;
}
digitalWrite(yellowLed, yellowLedState);
  } else{
  digitalWrite(yellowLed,LOW);
    }
}

if (buttonState2 == HIGH && yellowLedState == HIGH){
  digitalWrite(greenbigLed, HIGH);
}else{
  digitalWrite(greenbigLed,LOW);
}

}

Now, I'm able to pour out water when child lock feature activated, but the problem is the timer (interval) still ticking.

Is there any solution on how can I pause the interval whenever I'm pouring water (button2) and the interval starts back 5 sec when I release button2 (pouring water)?

I would glad if someone can help me. Ask me anything about my code.

Thanks @Arjan for reminding me. I would love to contribute to the community. So this is my final coding and its worked for me :

const int redLed = 2;
const int greenLed = 3;
const int yellowLed = 4;
const int greenbigLed = 7;

const int buttonPin1 = 5;
const int buttonPin2 = 6;

int buttonState1 = 0;
int buttonState2 = 0;
float tempC ;
int analogPin = A0;
int yellowLedState = 0;

const long interval = 5000;
unsigned long previousMillis = 0;

void setup() {
  // put your setup code here, to run once:
pinMode(2,OUTPUT);
pinMode(3,OUTPUT);
pinMode(4,OUTPUT);
pinMode(5,INPUT);
pinMode(6,INPUT);
Serial.begin(9600);
digitalWrite(yellowLed,yellowLedState);

}

void loop() {
  // put your main code here, to run repeatedly:
int analogValue = analogRead(analogPin);
int buttonState1 = digitalRead(buttonPin1);
int buttonState2 = digitalRead(buttonPin2);
int yellowLedState = digitalRead(yellowLed);
tempC = analogValue / 10 ;
Serial.println(tempC);
unsigned long currentMillis = millis();

if (tempC <= 89.9 && tempC >= 0){
  digitalWrite(redLed,HIGH);
  digitalWrite(greenLed,LOW);
}else if(tempC == 102){
  digitalWrite(redLed,LOW);
  digitalWrite(greenLed,HIGH);
}

if(currentMillis - previousMillis >= interval){
  previousMillis = currentMillis;
      if(buttonState1 == HIGH){
         if (yellowLedState == LOW) {
              yellowLedState = HIGH;
    }
    digitalWrite(yellowLed, yellowLedState);
  } else{
      digitalWrite(yellowLed,LOW);
    }
}

if (buttonState2 == HIGH && yellowLedState == HIGH){
  digitalWrite(greenbigLed, HIGH);
  digitalWrite(yellowLed,HIGH);
}else{
  digitalWrite(greenbigLed,LOW);
  if(currentMillis - previousMillis >= interval){
  previousMillis = currentMillis;
      if(buttonState1 == HIGH){
         if (yellowLedState == LOW) {
              yellowLedState = HIGH;
    }
    digitalWrite(yellowLed, yellowLedState);
  } else{
      digitalWrite(yellowLed,LOW);
    }
}
}
}


How to combine two codes in arduino? bine
#include <LiquidCrystal.h>
LiquidCrystal lcd(12,11,5,4,3,2);

#define sensor A0
#define led 13
#define ledd 8  // d out from mq3
#define buz 9
#define motor 10
void setup()
{
  Serial.begin(9600);
  lcd.begin(16,2);
  lcd.print("ALCOHOL MONITORING");
  lcd.setCursor(0,1);
  lcd.print(" VEHICLE SYSTEM ");
  delay(2000);
  pinMode(sensor, INPUT);
  pinMode(buz, OUTPUT);
  pinMode(led, OUTPUT);
  pinMode(ledd, OUTPUT);
  pinMode(motor, OUTPUT);
  lcd.clear();
}

void loop()
{
  float adcValue=0;
  for(int i=0;i<10;i++)
  {
    float actualanalogReading =  analogRead(sensor);
    adcValue = adcValue + actualanalogReading;
    Serial.println("In loop counter >"); // logging
    Serial.print(i);
    Serial.print(" input reading : ");
    Serial.print(actualanalogReading);
    Serial.print(" cumulative input reading : ");
    Serial.print(adcValue);

    delay(10);
  }
    float v= (adcValue/10) * (3.0/1024.0);
    float mgL= 0.67 * v;
    Serial.println("");
    Serial.print("Post calculation v value >" );
    Serial.print(v);
    Serial.print(" mg/L > ");
    Serial.print(mgL);
    Serial.println("");
    Serial.print("BAC:");
    Serial.print(mgL);
    Serial.print(" mg/L");
    lcd.setCursor(0,0);
    lcd.print("BAC: ");
    lcd.print(mgL,4);
    lcd.print(" mg/L        ");
    lcd.setCursor(0,1);
    if(mgL > 0.8)
    {
      lcd.print("Drunk ENGINE OFF ");
      Serial.println("Drunk ENGINE OFF ");
      digitalWrite(buz, HIGH);
      digitalWrite(led, HIGH);
      digitalWrite(ledd, LOW);
      digitalWrite(motor, LOW);
    }
    else
    {
      lcd.print("Normal ENGINE ON ");
      Serial.println(" Normal ENGINE ON ");
      digitalWrite(buz, LOW);
      digitalWrite(led, LOW);
      digitalWrite(ledd, HIGH);
      digitalWrite(motor, HIGH);
    }

    delay(100);

}

top code^^^
combines with this>>
const int LED = A5;
const int DO = 6;
void setup() {
 Serial.begin(9600);
 pinMode(LED, OUTPUT);
 pinMode(DO, INPUT);
}
void loop() {
 int alarm = 0;
 float sensor_volt;
 float RS_gas;
 float ratio;
//-Replace the name "R0" with the value of R0 in the demo of First Test -/
 float R0 = 0.10;
 int sensorValue = analogRead(A1);
 sensor_volt = ((float)sensorValue / 1024) * 5.0;
RS_gas = (5.0 - sensor_volt) / sensor_volt; // Depend on RL on yor module
 ratio = RS_gas / R0; // ratio = RS/R0
//------------------------------------------------------------/
 Serial.print("sensor_volt = ");
 Serial.println(sensor_volt);
 Serial.print("RS_ratio = ");
 Serial.println(RS_gas);
 Serial.print("Rs/R0 = ");
 Serial.println(ratio);
 Serial.print("\n\n");
 alarm = digitalRead(DO);
 if (alarm == 1) digitalWrite(LED, LOW);
 else if (alarm == 0) digitalWrite(LED, HIGH);
 delay(1000);
}

While I'd like to direct you to ways to set up a nice tasking system with a frame counter, your system is likely simple enough that it is unnecessary.  You can likely just replace the delay(1000); of the second program with approximately 5 calls of the first program's loop.  May you instead learn something when cleaning up the following (which is literally a copy paste with minimal changes).

#include <LiquidCrystal.h>
LiquidCrystal lcd(12,11,5,4,3,2);

#define sensor A0
#define led 13
#define ledd 8  // d out from mq3
#define buz 9
#define motor 10
void setup1()
{
  Serial.begin(9600);
  lcd.begin(16,2);
  lcd.print("ALCOHOL MONITORING");
  lcd.setCursor(0,1);
  lcd.print(" VEHICLE SYSTEM ");
  delay(2000);
  pinMode(sensor, INPUT);
  pinMode(buz, OUTPUT);
  pinMode(led, OUTPUT);
  pinMode(ledd, OUTPUT);
  pinMode(motor, OUTPUT);
  lcd.clear();
}

void loop1()
{
  float adcValue=0;
  for(int i=0;i<10;i++)
  {
    float actualanalogReading =  analogRead(sensor);
    adcValue = adcValue + actualanalogReading;
    Serial.println("In loop counter >"); // logging
    Serial.print(i);
    Serial.print(" input reading : ");
    Serial.print(actualanalogReading);
    Serial.print(" cumulative input reading : ");
    Serial.print(adcValue);

    delay(10);
  }
    float v= (adcValue/10) * (3.0/1024.0);
    float mgL= 0.67 * v;
    Serial.println("");
    Serial.print("Post calculation v value >" );
    Serial.print(v);
    Serial.print(" mg/L > ");
    Serial.print(mgL);
    Serial.println("");
    Serial.print("BAC:");
    Serial.print(mgL);
    Serial.print(" mg/L");
    lcd.setCursor(0,0);
    lcd.print("BAC: ");
    lcd.print(mgL,4);
    lcd.print(" mg/L        ");
    lcd.setCursor(0,1);
    if(mgL > 0.8)
    {
      lcd.print("Drunk ENGINE OFF ");
      Serial.println("Drunk ENGINE OFF ");
      digitalWrite(buz, HIGH);
      digitalWrite(led, HIGH);
      digitalWrite(ledd, LOW);
      digitalWrite(motor, LOW);
    }
    else
    {
      lcd.print("Normal ENGINE ON ");
      Serial.println(" Normal ENGINE ON ");
      digitalWrite(buz, LOW);
      digitalWrite(led, LOW);
      digitalWrite(ledd, HIGH);
      digitalWrite(motor, HIGH);
    }

    delay(100);

}

const int LED = A5;
const int DO = 6;
void setup() {
 setup1(); //Serial.begin(9600);
 pinMode(LED, OUTPUT);
 pinMode(DO, INPUT);
}
void loop() {
 int alarm = 0;
 float sensor_volt;
 float RS_gas;
 float ratio;
//-Replace the name "R0" with the value of R0 in the demo of First Test -/
 float R0 = 0.10;
 int sensorValue = analogRead(A1);
 sensor_volt = ((float)sensorValue / 1024) * 5.0;
RS_gas = (5.0 - sensor_volt) / sensor_volt; // Depend on RL on yor module
 ratio = RS_gas / R0; // ratio = RS/R0
//------------------------------------------------------------/
 Serial.print("sensor_volt = ");
 Serial.println(sensor_volt);
 Serial.print("RS_ratio = ");
 Serial.println(RS_gas);
 Serial.print("Rs/R0 = ");
 Serial.println(ratio);
 Serial.print("\n\n");
 alarm = digitalRead(DO);
 if (alarm == 1) digitalWrite(LED, LOW);
 else if (alarm == 0) digitalWrite(LED, HIGH);

 for(int dd = 0; dd < 5; dd++) loop1();
}


Arduino DUE and optocoupler 4N25 I'm using an Arduino Due board with an optocoupler 4N25 to simulate a button pressed.
I have to open and close a circuit that drive an actuator. In that circuit, when connected, with the tester I'm measuring 6V.

I connect the anode to the pin 12 and the cathode in series with a 150-ohm resistor to ground, and Collector and Emitter from optocopupler to the circuit (and a normal Blink example with the pin 12).

When optocoupler is fired on and off respectively with a tester I measure 0V and 1.7V in the arduino part, and 4V and 6V.

This is not enough and the actuator is always run. I'd like to read 0-6V instad of 4V-6V. Does this depends on how much current goes to the anode/cathode of the optocoupler? Do I have to change the resistor in the arduino part? Any kind of advice? What can I do?

I don't want to use relay because I have read that in respect to a relay they are faster, smaller, longer-lived and quieter.

It sounds like the 4N25 opto-coupler on its own can't do what you need because it's not designed to directly make/break a connection between a power source and its load (i.e. it isn't functionally equivalent to a relay).

Internally, the switching functionality is provided by an NPN photo-transistor. A typical open collector usage would be something like this:

(Image copyright Lewis Loflin: http://www.bristolwatch.com/ele/opto_isolated.htm)

The switch (S1) and the power source (Vi) on the left would be your Arduino. All the connections on the right would be part of your device (the actuator).

As you can see, you need 3 connections on the right: voltage source (Vcc), ground, and the output (Vo, which goes to your device). The circuit basically works by pulling the output (Vo) either up to Vcc to turn it on, or down to ground to turn it off.

It looks like all you have is Vcc and Vo, so this kind of configuration won't work. (Don't try to use the ground from your Arduino instead. That could cause various other problems.)

It should be possible to setup additional circuitry to act more like a Solid State Relay, but without a ground reference point it can be harder than it sounds. A mechanical relay might be the easiest option.


Connecting and using ESP8266 wifi My ESP8266 has stopped working.
The red power light comes on and the blue TX light is on solid.

Here's what I did.

Connecting

ESP8266  -> Arduino nano

VCC, CH_PD, RST  -> 5V (external supply)

TX -> TX

RX -> RX

I could send AT commands via the serial monitor.

Then I connected

RX -> 11

TX -> 10

and set up software serial intending to repeat the experiment.
I was getting garbage characters in the response, and found that I had to esp8266.println("AT+IPR=9600"); to reduce the baud rate.

Then the blue TX light cam on permanently and it's stopped working at all.

Serial devices should be connected RX to TX and TX to RX.

When you connected the RX to RX you connected the esp8266 to USB chip on Nano. Because the USB chip is connected to Atmega on Nano RX to TX, so if you connect the esp8266 to the same line, the it is connected RX to TX to USB.

On this picture esp8266 is connected to Atmega and not accessible from USB:

Communication from Serial Monitor over USB to esp8266 on pins 10 and 11 of the Atmega could work only with SerialPassthrough sketch resending data between Serial and SoftwareSerial on pins 10 and 11.


How to keep track of millis during sleep mode In my application, I need to keep track of the time the application has been running as well as use sleep modes. However, when using the sleep modes, Timer0 is disabled, and therefore millis stop counting.

Is there a way to measure/count how long the Arduino was in sleep mode for?

To give you some more background info, this is what I'm trying to achieve:
I am using a pressure sensor which sends an interrupt to the Arduino every 80ms and wakes it up.
The program does various routines to process the data which can take anywhere from 2ms to 60ms.
It then goes into sleep mode until another external interrupt occurs, approx 20-78ms later.
The application has many processes based on time, such as a stopwatch, timer and alarm, so I need to be able to keep track of this, preferably using millis().
The device is running on a single cell 250mah LiPo battery which at present only lasts about 4 hours.
I'm using an ATMega1284.

In most of the sleep modes Timer0 is disabled. Which means that millis() stops counting. Is there a way, without using an RTC (Both Space and weight are at a premium), to keep millis counting whilst in sleep mode?

I notice that SLEEP_MODE_IDLE keeps Timer0 running, but that means that for every millisecond an interrupt wakes up the device. Please correct me if I'm wrong, but given that my loop can take about 60ms to execute, I don't see much advantage to sleeping for 1ms.

Possible solutions:

Use Timer2 for the millis function?
Use the Watchdog Timer to count how much time has passed whilst in
sleep mode and add this to millis() when waking up?
If there was a VERY small SMD RTC which didn't need any external
components such as oscilators etc then this might be feasible.

The only way to keep millis() running is sleep mode is to sleep in
SLEEP_MODE_IDLE. Switching to Timer 2 would make no difference, as
all timers but the watchdog are stopped in other sleep modes. The
watchdog is horribly inaccurate, so you do not want to rely on it for
any kind of timekeeping.

  I don't see much advantage to sleeping for 1 ms.

Sleeping for 1 ms saves a little bit of power. But if you do that
60 times every 80 ms you will save a lot of power. I suggest
you do just that: sleep when you are done with your calculations. When
you wake up, if you see that the waking up came from the external
interrupt, the you process it. Otherwise you just go back to sleep.

Note that if the 80 ms period of the external interrupt is
consistent enough, you could use that as time source.


INPUT_PULLUP not work for D8 in my NodeMCU v3 I changed my arduino NodeMCU application pin mode to use INPUT_PULLUP mode instead of INPUT. D8 input pin is not working as expected, I is always in LOW even the button is pressed or not.

I have 3 input pins (D2, D7, D8), when I changed to internal pull up resistor, I removed each external resistors from input and changed the circuit accourding to this: https://www.arduino.cc/en/Tutorial/InputPullupSerial

D2 and D7 works well, but D8 is not. I checked with a volage between GND and pins:

when button on D2, D7 is not pressed: 2.95 - 3 V
when button on D8 is not pressed: 0.8 V
when button on D2, D7, D8 is pressed: 0V (as expected)

You can see my code in github:
https://github.com/kisdaniel/HomeDashboardGarageDoorOpener

Pin D8 is esp8266 pin 15. This pin is one of the boot configuration pins and for use on a dev board, it must be pulled down at boot. So the NodeMcu has a pull down circuit on this pin and internal pullup is weaker then this external pulldown.


Weird behavior with char/uint8 arrays So I'm trying to read an 8-byte character string from an I2C device and print it to the serial console. This raw 8-char array is not terminated when it comes from the device, so I'm pretty sure I need to manually terminate it. Unfortunately, when I go to print the resultant string, the serial monitor just fills up with line breaks. Could someone take a look at this code and tell me where I went wrong?

uint8_t* HT_Controller::readMultiple(uint8_t reg, uint8_t num)
{
    Wire.beginTransmission(i2cAddr);
    Wire.write(reg);
    Wire.endTransmission();

    Wire.requestFrom(i2cAddr, num);
    uint8_t* data = new uint8_t[num];

    for(int i = 0; i < num; i++)
    {
        data[i] = Wire.read();
    }

    return data;
}

char* HT_Controller::getManufacturer()
{
    uint8_t* data = readMultiple(REGISTER_MFR, NUM_MFR_BYTES); //Read the bytes from the controller
    char* dataTerminated = new char[NUM_MFR_BYTES + 1]; //Our new array that will have a null char at the end
    memcpy(data, dataTerminated, NUM_MFR_BYTES); //Copy the bytes into the new array
    delete(data); //We're done with the original array, remove it from the heap
    dataTerminated[NUM_MFR_BYTES] = 0; //Add that null char. NB: we don't need to '+1' the index because arrays start at 0, not 1

    return dataTerminated;
}

And here's how it's used in the main sketch:

void loop()
{
    char* data = mc1->getManufacturer();
    Serial.println(data);
    delete(data);
    delay(500);
}

Your memcpy is backwards.

SYNOPSIS
   #include <string.h>

   void *memcpy(void *dest, const void *src, size_t n);

So the line:

memcpy(data, dataTerminated, NUM_MFR_BYTES); //Copy the bytes into the new array

should be:

memcpy(dataTerminated, data, NUM_MFR_BYTES); //Copy the bytes into the new array


Getting coordinates from a touch panel with I2C Hello world (this is my first message in this forum).

I am quite a just-married-to-Arduino guy, I am very passionate about this platform that I kew since long time but never had the time to dedicate.

Now I have done several home projects that made me both feel happy and feel sooooo rookie... But hey, here I am trying more and more complex things.

I am trying to do something I haven't found information about: I have a 10" touch panel (I am not talking about a screen, just the touch surface) which is a capacitive 10 pin panel that communicates with I2C protocol (there are SCL and SDK pins). I have managed to scan the address and turns out it is in the #40.

However, other than that I do not have the knowledge to get the coordinates out of that panel. My question is: is there any library that can help me with that or will I need to code everything?

I am attaching some pictures of the panel and the pinout to have a clearer picture of what I am talking about.

I thank you all for your time reading my post, I hope some day I will be able to provide some answers rather than questioning!

Joan.

There is a simple library that works for FT5xx6 display panel.

Other information available:

Application node - https://cdn-shop.adafruit.com/datasheets/FT6x06_AN_public_ver0.1.3.pdf

Datasheet - https://www.newhavendisplay.com/appnotes/datasheets/touchpanel/FT5x26.pdf

In case those links might be no longer available in the future, a quick search on FocalTech FT5xx6 should give you the relevant information.


Why is my relay not triggering? I have a 4 channel relay for my Arduino. Here's an image:

From what I can tell, it's rated for 5V direct current because of the big 05VDC at the bottom, but please tell me if I'm wrong? If I'm wrong, then that's the problem here.

I've tested out an LED on 5V DC to work and connected it to output side of the relay.

I've connected my Arduino to the input, programmed with the following code:

const int RELAY_PIN = 3;

void setup() {
  pinMode(RELAY_PIN, OUTPUT);
  Serial.begin(96000);

}

void loop() {
  Serial.println("Relay ON");
  digitalWrite(RELAY_PIN, LOW);
  delay(1000);

  Serial.println("Relay OFF");
  digitalWrite(RELAY_PIN, HIGH);
  delay(1000);
}

I can confirm that the corresponding LED on the relay for channel 4 does blink for 1 second and stay off for 1 second, which I'm expecting it's meant to do. I've never worked with an Arduino or a relay before.

However, the 5V DC LED on the other end never lights up. Why is my relay not switching on?

Edit: About the LED circuit. It is on and fully powered. If I bypass the relay and join the two wires, the LED lights up. If I plug the two wires into the relay, the LED never lights up.

Edit2: About the jumper: I have a secondary 5V power supply connected to the VCC for what I'm told is isolation. I've read a little on the matter, but am not fully aware of how it works.

Edit 3:

Connections

I have the following connections:

Output 3 (Arduino) to Input 4 (Relay)
5V (Arduino) to Input VCC (Relay) [The one next to the input pins]
Power supply positive/ground to GND (Relay)
Power supply negative/live to VCC (the one next to the JD-VCC)

This did not work. What did work was the following configuration:

Output 3 (Arduino) to Input 4 (Relay)
5V (Arduino) to Input VCC (Relay) [The one next to the input pins]
Jumper across VCC and JD-VCC on the Relay

From the image in the question, the jumper across pins J5 (in the
below schematic) or JD as on the silk screen on the PBC is missing.

Using the above schematic, a choice to power the Ardino and the relays off of one 5V power supply can be made.  This appears to be done by connecting the 5V to the VCC pin, Ground to the GND pin & placing a jumper across J5.  However, it appears that the relays can be isolated from the Arduino if desired.  This appears to be done by connecting the Arduino's 5V to pin 2 of J5.  That should be enough to light up the LED indicator and therefor the optical isolator when the Arduino's output to IN1, 2, 3 or 4 is low.  Then, connect the 2nd power source 5V to pin 1 of J5 and the ground from the 2nd power source to pin GND.  This last step should provide the power to close the relays when the Arduino takes IN1, 2, 3 or 4 low.
Lastly, make sure the polarity of the 2nd power supply (if one is used) is correct.  The output side of the optical coupler and the transistor driving the relay only work when the current is passing in the proper direction. Not to mention, the reverse bias flyback diode (D1, 2, 3 & 4) would short out the power supply if connected in the reverse direction.  However, this catastrophe is avoided here as the transistors (Q1, 2, 3 & 4) would not pass current in the reversed direction.


Arduino reading value from external devices on For this device it says:

The PC Interface Option has all the features of the standard DC1100, but also has a COM Port interface that allows you to capture the air quality data to a PC for graphing and analysis. A 9pin serial cable or USB-to-COM Port Adapter (not included) links the DC1100 to your PC or laptop which then captures the data as it samples.

Is it possible to connect such a device directly to an Arduino so that measured data are sent through the Serial Interface and Arduino is able to read them and manipulate them?

Yes, with a small converter board it can be connected to an Arduino. The "9 pin serial cable" is very likely an RS-232 interface.

RS-232 is like UART with a few extra connections. Here is what the cable looks like:

Basically UART with flow control and other modem lines. Most likely it hasn't any of them conencted but that standard RXD, TXD and GND. These are all the connections needed for the microcontroller.

The voltage level of RS232 is however specified in a wide range (plus/minus 3V to 25V), so you need a converter chip (e.g. this one with a MAX3232, search for "RS232 to TTL Converter Board"). You need to measure the voltage levels with a multimeter to see what converter for what voltage rage you need.

Then conencting it to an Arduino is as simple as just connecting these 3 wires to the Arduino, either to the Hardware Serial port (D0, D1, GND) or via a software serial port.

Reference project:

http://www.picprojects.net/rs232_communication/

However, receiving the communication data is only half the battle. You still have to figure out what the sent data represents and what commands you can send the device. Without datasheets from the vendor, you are left alone. This is where reverse-engineering starts.

As a starting point, you can "eaves-drop" on the communucation that PC software does with the device by just connecting a USB-RS232 converter to your computer and connecting the RX line line to either the TX or RX line of the the target device's COM port. This allows you to see the entire communication exchange. From this you might be able to see what commands you're supposed to send. But as I said, from there it's unchartered territory.


How to connect NodeMCU to NRF24L01 I need to connect NodeMCU and NRF24L01. where I'm receiving data from another NRF24L01 Transmission. I managed to connect to a WiFi network but the data receiving is not taking place as expected. Here is my code

#include <SPI.h>
#include "RF24.h"
#include <ESP8266WiFi.h>

RF24 myRadio(7, 8);
const char* ssid = "******";
const char* password = "********";
struct package
{
    int id = 0;
    float longitude = 0.0;
    float latitude = 0.0;
    char text[100] = "empty";
};

byte addresses[][6] = {"0"};

typedef struct package Package;
Package data;

void setup()
{
    Serial.begin(115200);
    delay(1000);
    WiFi.begin(ssid, password);

    Serial.println();
    Serial.print("Connecting");
    while (WiFi.status() != WL_CONNECTED)
    {
     delay(500);
     Serial.print(".");
    }
    Serial.println("success!");
    Serial.print("IP Address is: ");
    Serial.println(WiFi.localIP());
    myRadio.begin();
    myRadio.setChannel(115);
    myRadio.setPALevel(RF24_PA_MAX);
    myRadio.setDataRate(RF24_250KBPS);
    myRadio.openReadingPipe(1, addresses[0]);
    myRadio.startListening();
}

void loop()
{

    if (myRadio.available())
    {
        while (myRadio.available())
        {
            myRadio.read(&data, sizeof(data));
        }
        Serial.print("\nPackage:");
        Serial.print(data.id);
        Serial.print("\n");
        Serial.println(data.longitude);
        Serial.println(data.latitude);
        Serial.println(data.text);
    }
}

Any idea on why this is not receiving data as expected?. This somehow managed to connect to my WIFI successfully. Here are my pin connection

The Dx pin labels on NodeMcu and Wemos/Lolin boards do not correspond to esp8266 internal io pin numbers. The pins_arduino.h file in core defines Dx constants which map internal io numbers to Dx labels.

Use RF24 myRadio(D7, D8);


External power vs usb power I built a sample of my project on a breadboard using little 700mh leds and other components that easily ran off my computers usb. Now I’m building my project to full size.  This includes 12 7w leds, soundboard and amps. It’s still going to be controlled by a arduino mega, obviously, the power consumption is substantially higher than the usb or even the arduino can provide. I’m using a high amp power supply that can drive everything including the arduino.

The question is... how will I be able to alter my sketch later???  Is it feasible to use a panel mount usb cord modified to only allow tx and rx, (cut the red and black)?  Or will I have to isolate the mega each time I need to send a change to it?

You can modify a USB cable by cutting the power (red) wire. You'll still need the ground wire with RX and TX.


Arduino Yun external antenna Can someone help me understand how the external antenna IPX connector actually stays connected to the Yun? Do I have to "force" it in so it snaps in? I've been somewhat gentle with it in fear I'll break something. However when I get close to getting it in, it just pops back out.

I've never worked with an IPX connector before, and I'm trying to not break anything.

EDIT: I may have figured this out. Looks like the socket on the Yun is an IPEX socket, which is female. The cable I have is an IPX/uFL/u.FL connector, which also appears to be female.

It looks like I need to use an MCX cable adapter as found here: http://www.adafruit.com/products/1532 If someone could confirm this for me, that'd be great.

Here's a picture of the cable I purchased and my Yun.

There's a discussion on the Arduino Forum about this:

Mystery component on Yun board?

From what I read it's only for testing purposes.

  the connector is a MM8430-2610 (see this). You can plug in a
  MXGS83RK3000/MM126036: once plugged in, the switch connector will turn
  the internal antenna off and use the probe as an external antenna


How can I increase the torque or speed of the stepper motor with Arduino I run 28BYJ-48 12 Volt Motor with ULN 2003 Driver using Arduino UNO.
I am also using external 12 volt power outside.
I aim for the syringe pump to move back and forth with the rotation of the motor.
I'm using the code below.
The code is running but the motor cannot move the syringe back and forth.
How do I change to be able to move the syringe pump
const int motorPin1 = 8;
const int motorPin2 = 9;
const int motorPin3 = 10;
const int motorPin4 = 11;

int bekleme =2
;
// bekleme süresini değiştirerek step motorun hızlı veya yavaş ilerlemesini sağlayabilirsiniz.
//1sn=1000

void adim1() {
digitalWrite(motorPin1, HIGH);
digitalWrite(motorPin2, LOW);
digitalWrite(motorPin3, LOW);
digitalWrite(motorPin4, LOW);
delay(bekleme);
}

void adim2() {
digitalWrite(motorPin1, LOW);
digitalWrite(motorPin2, HIGH);
digitalWrite(motorPin3, LOW);
digitalWrite(motorPin4, LOW);
delay(bekleme);
}

void adim3() {
digitalWrite(motorPin1, LOW);
digitalWrite(motorPin2, LOW);
digitalWrite(motorPin3, HIGH);
digitalWrite(motorPin4, LOW);
delay(bekleme);
}

void adim4() {
digitalWrite(motorPin1, LOW);
digitalWrite(motorPin2, LOW);
digitalWrite(motorPin3, LOW);
digitalWrite(motorPin4, HIGH);
delay(bekleme);
}

void setup() {

pinMode(motorPin1, OUTPUT);
pinMode(motorPin2, OUTPUT);
pinMode(motorPin3, OUTPUT);
pinMode(motorPin4, OUTPUT);

}

void loop() {

for (int i = 0; i < 2048 ; i++)
{
adim1();
adim2();
adim3();
adim4();
}
{

exit(0);
}
}

İleri
// Meraklı Mühendis Sayfasının hazırlığı kodlar kullanılmıştır.
//Dilerseniz farklı fonksiyonlar kullanabilirsiniz.

const int motorPin1 = 8;
const int motorPin2 = 9;
const int motorPin3 = 10;
const int motorPin4 = 11;

int bekleme =2;
// bekleme süresini değiştirerek step motorun hızlı veya yavaş ilerlemesini sağlayabilirsiniz.
//1sn=1000

void adim1() {
digitalWrite(motorPin1, HIGH);
digitalWrite(motorPin2, LOW);
digitalWrite(motorPin3, LOW);
digitalWrite(motorPin4, LOW);
delay(bekleme);
}

void adim2() {
digitalWrite(motorPin1, LOW);
digitalWrite(motorPin2, HIGH);
digitalWrite(motorPin3, LOW);
digitalWrite(motorPin4, LOW);
delay(bekleme);
}

void adim3() {
digitalWrite(motorPin1, LOW);
digitalWrite(motorPin2, LOW);
digitalWrite(motorPin3, HIGH);
digitalWrite(motorPin4, LOW);
delay(bekleme);
}

void adim4() {
digitalWrite(motorPin1, LOW);
digitalWrite(motorPin2, LOW);
digitalWrite(motorPin3, LOW);
digitalWrite(motorPin4, HIGH);
delay(bekleme);
}

void setup() {

pinMode(motorPin1, OUTPUT);
pinMode(motorPin2, OUTPUT);
pinMode(motorPin3, OUTPUT);
pinMode(motorPin4, OUTPUT);

}

void loop() {

for (int i = 0; i <2048; i++)   // buradaki 512 değerleri step motorun tam bir tur dönmesini sağlıyor. dilerseniz bu sayıyı değiştirebilirsiniz
{
adim4();
adim3();
adim2();
adim1();

}
{

exit(0);
}
}

To increase torque of 28BYJ-48 you have to perform a simple mod (cup one path on the PCB) to change it from unipolar to bipolar and then use it with an H-bridge like the A4988 or the DRV8825 driver.

Sources:

https://ardufocus.com/howto/28byj-48-bipolar-hw-mod/
https://coeleveld.com/wp-content/uploads/2016/10/Modifying-a-28BYJ-48-step-motor-from-unipolar-to-bipolar.pdf
https://everythingsmarthome.co.uk/howto/converting-the-28byj-48-stepper-motor-for-more-torque/
http://www.jangeox.be/2013/10/change-unipolar-28byj-48-to-bipolar.html
https://www.youtube.com/watch?v=hkxnQIKybiI
https://www.youtube.com/watch?v=jHLyJbNgcDo


Basic Arduino Question. Trying to turn off leds turned on through the serial monitor by using a push button I'm new to using the serial monitor. I have a code set up so that LEDs turn on when I type an input on the keyboard. I know how to turn them off using a keyboard but I and can't figure out why the leds won't turn off when I press a push button.

    #define led1 10 //10th,
    #define led2 11 //11th
    #define led3 12 //12th
    #define led4 13 //13th
    #define ButtonA 9

    int ButtonState;
    int ButtonState2;
    int state;
    int StateNow;
    int PreviousState = HIGH;

    void setup(){
      pinMode(led1,OUTPUT);
      pinMode(led2,OUTPUT);
      pinMode(led3,OUTPUT);
      pinMode(led4,OUTPUT);
      pinMode(ButtonA,INPUT_PULLUP);
      Serial.begin(9600);
      Serial.println("Enter ch a, b, c, or d:");
    }

    void loop() {
    if (Serial.available())
    {
      ButtonState = digitalRead(ButtonA);
      delay(10);
      ButtonState2 = digitalRead(ButtonA);  //debounce
      if (ButtonState != ButtonState2)
      {
        StateNow = ButtonState2;
      }
      else
      {
        StateNow = ButtonState;
      }
      if(StateNow == LOW && PreviousState == HIGH)
  {
    digitalWrite(led1,LOW);
    digitalWrite(led2,LOW);
    digitalWrite(led3,LOW);
    digitalWrite(led4,LOW);
    Serial.println("Turned off all LEDs");
    PreviousState = LOW;
  }
  else if(StateNow == HIGH && PreviousState == LOW)
  {
    PreviousState = HIGH;
  }
  state = Serial.read();
  if (state == 'a' || state == 'A')
  {
    digitalWrite(led1,HIGH);
    Serial.println("Turned on led 1");
  }
  else if (state == 'b' || state == 'B')
  {
    digitalWrite(led2,HIGH);
    Serial.println("Turned on led 2");
  }
  else if (state == 'c' || state == 'C')
  {
    digitalWrite(led3,HIGH);
    Serial.println("Turned on led 3");
  }
  else if (state == 'd' || state == 'D')
  {
    digitalWrite(led4,HIGH);
    Serial.println("Turned on led 4");
  }
}

}

The LEDs turn on properly and I know the circuit is wired correctly so it's definitely something I'm missing in the software

To turn off all leds when button is pressed, you must detect a rising or falling in the button signal.

In your code you detect the change only if serial is available, but you should do it in the loop.

The simple way to detect the change is doing this in every loop:

if (StateNow != PreviousState) {
  if (StateNow == LOW && PreviousState == HIGH) //button pushed
  {
    digitalWrite(led1, LOW);
    digitalWrite(led2, LOW);
    digitalWrite(led3, LOW);
    digitalWrite(led4, LOW);
    Serial.println("Turned off all LEDs");
  }
  PreviousState = StateNow;
}

I simplify your code and add some comments:

#define led1 10 //10th,
#define led2 11 //11th
#define led3 12 //12th
#define led4 13 //13th
#define ButtonA 9

int state;
int StateNow;
int PreviousState;

void setup() {
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);
  pinMode(led4, OUTPUT);
  pinMode(ButtonA, INPUT_PULLUP);
  Serial.begin(9600);
  Serial.println("Enter ch a, b, c, or d:");
  PreviousState = digitalRead(ButtonA);
}

void loop() {
  //detect changes in button signal to turn off leds
  StateNow = digitalRead(ButtonA);
  if (StateNow != PreviousState) {
    if (StateNow == LOW && PreviousState == HIGH) //button pushed
    {
      digitalWrite(led1, LOW);
      digitalWrite(led2, LOW);
      digitalWrite(led3, LOW);
      digitalWrite(led4, LOW);
      Serial.println("Turned off all LEDs");
    }
    PreviousState = StateNow;
  }

  //check serial biffer to turn on leds
  if (Serial.available())
  {
    state = Serial.read();
    if (state == 'a' || state == 'A')
    {
      digitalWrite(led1, HIGH);
      Serial.println("Turned on led 1");
    }
    else if (state == 'b' || state == 'B')
    {
      digitalWrite(led2, HIGH);
      Serial.println("Turned on led 2");
    }
    else if (state == 'c' || state == 'C')
    {
      digitalWrite(led3, HIGH);
      Serial.println("Turned on led 3");
    }
    else if (state == 'd' || state == 'D')
    {
      digitalWrite(led4, HIGH);
      Serial.println("Turned on led 4");
    }
  }
}


How to send chars and values at the same time from processing to Arduino i have been trying to set Builtin LED frequency from arduino and turn it on and off .

I have created an interface with knobs and buttons in processing . I want to set delay between ON and OFF with 1 knob and OFF and ON delay with another knob . And button blinks the led at given frequency

In arduino i have tried something like this :

if(Serial.available() >0){
char val=Serial.read();
switch(val)
{
  case 'c':
  theValue=Serial.read();
  break;
  case 'd':
  theValue1=Serial.read();
  break;

case 'r':
digitalWrite(13,HIGH);
delay(theValue);
digitalWrite(13,LOW);
delay(theValue1);

break;
}

}

In the processing :

  public void Blink(){
   myPort.write('r');
 }

 public void knobON(int theValue){
   myPort.write('c');
   myPort.write(theValue);
 }

 public void knobOFF(int theValue1){
   myPort.write('d');
   myPort.write(theValue1);
 }

Can you help me on what should i do ?

The Arduino code sample you've provided is incomplete, and does not compile. On the Processing side, I would combine the LED On time with the Off time, using a separator, then ending with a \n. Something like this: myPort.write("1000:2000\n");.

There are many ways to parse the serial data into unsigned long to be used in the delay() function. Here is a sketch illustrating one way to parse it. I am using the serial monitor to send the following test data 1000:2000 (LED on for 1 second, off for 2 seconds). The serial monitor is sending the \n character.

char buffer[16];
unsigned long onTime;
unsigned long offTime;

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

void loop(){

  if(Serial.available() > 0){

    Serial.readBytesUntil('\n', buffer, 13);

    char * pch;
    pch = strtok(buffer, ":");
    onTime = strtol(pch, &pch, 10);
    pch = strtok(NULL, ":");
    offTime = strtol(pch, NULL, 10);

    digitalWrite(13, HIGH);
    delay(onTime);
    digitalWrite(13, LOW);
    delay(offTime);
    memset(buffer, 0, sizeof(buffer));
  }
}


Can a timer be used in both CTC and (fast) PWM mode simultaneously? I would like to generate a sequence of pulses of varying lengths in the range of 0-100us, so that from the start of one pulse to the start of the next there is a delay of 100us. I have set up timer0 in CTC mode to trigger an interrupt every 100us.

In this interrupt, I would like to turn the appropriate pin high, read the length of the current pulse from an array, and then configure the timer in such a away that it turns the pin off as soon as the pulse length has elapsed (I am hoping that this is possible without using an interrupt for turning off the pin). It seems that the PWM functionality can do what I want, if I use the second output compare register.

In any case this seems possible using a secondary timer in PWM mode, but I'd like to know whether the same is possible using only a single timer. From what I've seen in the datasheets the answer seems no, but perhaps I am missing something.

Can a timer be used in both CTC (with output compare register A) and PWM modes (with output compare register B)?

Technically no. CTC and PWM are distinct modes of operation.

However, more advanced PWM modes, specifically mode 7 for 8-bit timers and modes 14 and 15 for 16-bit timers, allow specifying an arbitrary timer duration in OCRxA or ICRx while still allowing PWM operation using the other output compares.


How to set Inquire Access Code (IAC) via AT commands on HC-05? I am trying to set IAC of HC05 via AT Commands, but for some reason, the result is not as desired.

I need to set the IAC as '1234', for which I enter the command:

AT+IAC=1234

The module responds OK, but when I ask AT+IAC?, it replies '01234'.

Now, it has been troubling me for the past few days. I've also tried adding '\r\n' to the end of command, but it sets the IAC as '1234444'

I would be thankful if you could help me with this! I tried searching the net but to no avail.

You have to have \r\n in both the set and read command.

Example:

AT+IAC=12345f\r\n
OK

AT+IAC?\r\n
+IAC: 12345f
OK


Why does it say "Servo" does not name a type #define pingTrig 6
#define pingEcho 7

#include

Servo myservo;

void setup()
{
pinMode(pingTrig, OUTPUT);
pinMode(pingEcho, INPUT);
myservo.attach(9);
}

void loop()
{
long duration, inches, cm;

digitalWrite(pingTrig, LOW);
digitalWrite(pingTrig, HIGH);
delayMicroseconds(10);
digitalWrite(pingTrig, LOW);

duration = pulseIn(pingEcho, HIGH);

cm = duration / 29 / 2;

if(cm < 10 ){
myservo.write(90);
delay(100);
}else{
myservo.write(0);
}
delay(2000);
}

Your include statement seems to be incomplete; add "Servo.h" to your include to make it look like this:

#include "Servo.h"

Without including "Servo.h", the compiler doesn't know what a servo is, and thus "Servo does not name a type".


Can't send SoftwareSerial to Class Object I have a problem when I try to use SoftwareSerial in a class..

Here my detail My class

class MyEsp8266
{
 protected:
     SoftwareSerial *esp8266;
 public:
     MyEsp8266(SoftwareSerial *_esp8266){
           esp8266 = _esp8266;
     }
     void begin(int baud){
        esp8266->begin(baud);
     }
     String testAT(){
          esp8266->println("AT");
          return esp8266->readString();
     }
}

My Arduino code

#include <SoftwareSerial.h>
#include "MyEsp8266.h"
// the setup function runs once when you press reset or power the board

SoftwareSerial _esp(10, 11);
MyEsp8266 wifi(&_esp);

void setup() {
    Serial.begin(9600);
    wifi.begin(115200);
    Serial.println(wifi.testAT());
}

It doesn't log anything But when I have used all code in Arduino code it worked.

#include <SoftwareSerial.h>
// the setup function runs once when you press reset or power the board

SoftwareSerial _esp(10, 11);

void setup() {
    Serial.begin(9600);
    _esp.begin(115200);
    _esp.println("AT");
    Serial.println(_esp.readString());
}

Thank any tips.
Regards.

This is more of a work-around than a solution, but the code you're trying to get to work, worked for me once I changed

wifi.begin(115200);

to

wifi.begin(9600);

(sorry I don't have enough karma to just comment)


Reverse engineering of a bluetooth sensor I have a problem.
I'm trying to trigger some events with Arduino using some bluetooth LE sensor by a chinese manufacturer, Kaipule. I buy this sensor on Alibaba and I'm trying to understand how can I interface them in my sketch.

They are magnetic contact sensors and I know that they have just the BLE broadcasting mode (no GATT, profile etc): they send information when I open the contact or I close the contact.

I try to scan them with a BLE scanner and this is the log

kCBAdvDataIsConnectable : 0
Local Name : iSensor
Manufacturer Data : <beca2c02 4602f9f7>

I know that:

1) the scanner can see the sensor just when I open/close the contact to save battery, so the sensor broadcast data just when it need.

2) every hour the sensor send a status signal

3) every time I open and close the contact the code change a little. Here is a sequence

<beca2c02 46025856> - > open
<beca2c02 46005955> - > close
<beca2c02 46025a58> - > open
<beca2c02 46005b57> - > close
<beca2c02 46025c5a> - > open
<beca2c02 46005d59> - > close
<beca2c02 46025e5c> - > open
<beca2c02 46005f5b> - > close

etc

4) The first part of the code is the identification of the sensor.

3) From the changing code I assume that 2 is the status open, 0 is the status close and I see also a pattern for other bytes but I cannot understand why for example there is a rolling code.

I have the paper the company send to me, but I cannot find any useful reference.

Wireless sensor 1
Wireless sensor 2

Looking at the datasheet, I interpreted it as:

Byte 1 - 0x46

Indicating this is a unidirectional device (bit7=0) that uses fixed time sending (bit 6=1 which doesn't seem correct) and it is of type 'door contact' (bits 0-5=0x06)

Byte 2 - 0x00/0x02

Indicating that the door is open or closed (bit 1 = 0 or 1). I also think that it indicates there is 'enough battery power' (bit 2 = 0), and the 'anti-tamper' has not been activated (bit 0 = 0)

Byte 3 - 0xXX

This is the 'Frame ID' - counting up for 0x40, to 0x5F then looping ?

Byte 4 - 0xXX

Checksum.

I'd do three things to test this theory:

Run the battery down a lot and see if the battery power indicator changes (byte 2, bit 2).
Open the case and see if the 'anti-tamper' bit changes (byte 2, bit 0)
Do sufficient switching to determine if byte 3 loops around as expected.

This these don't work out then you're likely looking at a different model.


NRF24L01 Transmission Problems between Arduino UNO and Arduino Nano I'm a beginner in using NRF24L01 tranceiver module. I tried sending a simple "Hello world" using Arduino Nano and a Arduino UNO with the use of two NRF24L01 modules. I don't get any output in the serial monitor at the receiver side. I checked the wire connection numerous times. Also checked the baud rate of both receiver code and the serial monitor are same and adddresses of the tranceiver code and the receiver code are same. Looking for a solution. Thanks in advance.
This is my tranceiver code:
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
RF24 radio(7, 8); // CE, CSN
const byte address[6] = "00001";
void setup() {
  radio.begin();
  radio.openWritingPipe(address);
  radio.setPALevel(RF24_PA_MIN);
  radio.stopListening();
}
void loop() {
  const char text[] = "Hello World";
  radio.write(&text, sizeof(text));
  delay(1000);
}

And this is my Receiver code:
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
RF24 radio(7, 8); // CE, CSN
const byte address[6] = "00001";
void setup() {
  Serial.begin(9600);
  radio.begin();
  radio.openReadingPipe(0, address);
  radio.setPALevel(RF24_PA_MIN);
  radio.startListening();
}
void loop() {
  if (radio.available()) {
    char text[32] = "";
    radio.read(&text, sizeof(text));
    Serial.println(text);
  }
}

I had the same problem and when I tried the isChipConnected () function, it told me that one of the nrf24l01 was not connected to the SPI and I assumed that one was bad. I bought 2 nrf24l01 with antenas and they work well (mostly). ( Here is the link to the library reference. Also, make sure you are using the TMRh20 version of the library, This one. This is more updated and better as far as I'm aware.
Like everyone would suggest, try to solder a 10uF capacitor between GND and VCC (that module requires more power sometimes). And the last thing I tried was to use one of this socket adaptors for the 2 modules here to use the 5v output from the arduino since it can deliver more mA and thus the module can work better.
This guide help me a little bit, I'll drop it here
I don't see anything wrong in the code, but I'm a newbie like you so (It seems we are using the same adress in our codes)


Trying to read analog signal with digital pin using outside ADC Is there a way to route an analog signal from a simple temperature sensor through an ADC, MCP3008, into a digital pin. I have used all the analog pins on my Arduino  Mega 2560 and am trying to utilize all the digital I/Os.

Any insights on the matter would be greatly appreciated.

The MCP3008 is an SPI device. You connect it to the SPI pins of your Arduino. Then you can read 8 analog channels through it.

It requires 4 pins: MISO, MOSI, SCK and a chip select pin.


Using Interrupt on Arduino I'm currently working on a project in which I'm supposed to make an Arduino car dodge any kinds of obstacles. I know how to do without using Interruptions but as I was searching online I found out that this is something that is used and would turn out better. Is it really possible? And if so, I don't exactly grasp the concept of using it to make (for example) the car stop once it senses an object. I know that it is supposed to be the first thing it will do if I program it that way but, can I program how the Interrupt will act upon the machine? And if so, how exactly?

Thanks

Interrupts help if an event needs to be dealt with over the time period of a few processor clock cycles. Such as the deployment of air bags.  If the accumulated delay of not responding in a few processor clock cycles adds up to considerable error.  Such as a Real Time Clock (RTC). Or, if an event is so short that it might be missed during periodic polling (checking). Such as counting flashes of lighting during a storm.

If this type of response time is not needed, interrupts may be more trouble than they are worth.

This is because interrupts can stop the processor from executing the normal program and force it to execute the interrupt program.  This can be very confusing to new programmers.  At any moment an interrupt may stop their program and possibly erase or change what that program was working on.  Both the program that is running and the interrupt program need to be written to tolerate this processor behavior.

It is almost always easier to "poll" the state of obstacle sensors (in this case) rather than tying its state to an "interrupt".  Using the Arduino paradigm, the purposes of the loop() entry point is to do just this.  A function which will be called over and over again.  Each time it is called you can "poll" the sensor and cause the model car to vier around an obstacle.


How to multiply strings? I want to have a line like this

Serial.println(count*"B");

So if count=6, it would print BBBBBB, etc.

Is there anything like this for arduino?

You can write a helper function to do it, like this:

void printRepeat (Stream & device, const char * str, unsigned int count)
  {
  while (count-- > 0)
    device.print (str);
  }   // end of printRepeat

void setup()
  {
  Serial.begin (115200);
  printRepeat (Serial, "-", 20);
  Serial.println ();
  } // end of setup

void loop()
{
  printRepeat (Serial, "Hello, World! ", 5);
  Serial.println ();
  delay (500);
} // end of loop

The function printRepeat is passed a Stream argument, which can be something like Serial, Serial1, a SoftwareSerial instance, and so on.


Using a library of sleeping with a combination of the WD and a physical INTERRUPT I would like to use one of the nice libraries like :

JEELIB
ENERLIB
SLEEP_N0M1
NARCOLEPTIC
ADAFRUITSLEEPY_DOG
LOW_POWER_MASTER

But to use a X second interval of sleeping and in the same time to enable the option of an Interrupt on pin2 that will get me out of all this sleepy mode vector if there will be interrupt ! which library is better and easier for this situation?
when I want more then 8 second , what is the mining of doing 2x8s when they wrote it in some of those libraries -what should it mean to do ?
Is there an option to enable the interrupt for a wake up from the sleep not only by a LOW_mode but also by a CHANGE_mode of the pin2 ??

Thank you very much in advanced @!

"Best" is completely subjective. I've used Narcoleptic myself. it's easy to use and somewhat limited. For the needs of my project, it served well. You'll need to review the libraries' source code and descriptions to decide which library will best serve your application.
The Watchdog timer has a maximum interval of 8 seconds. To sleep longer, you'll need a routine that counts enough 8 second sleeps, plus lesser sleep periods, to make up the total sleep time you want. There are other timers you can use, but not in Power Down sleep mode.
See section 10, "Power Management and Sleep Modes" of the ATmega328p datasheet (or the datasheet for the chip your Arduino uses). There is a table of wake-up sources for each sleep mode. It says that, except from Idle mode, only a level-triggered interrupt can wake the chip. But note that section 10.5 says a pin-change interrupt can wake the CPU. It appears that either kind can wake it but "the required level must be held long enough for the MCU to complete the wake-up to trigger the level interrupt." It does not mention the (obviously transient) pin-change interrupt. You may need to experiment.

Update:

  ...I cant get a sleep for more than 8 second but I can only get to a sleeping mode twice and by that to get almost a 16 second of sleeping ?

Yes, the longest Watchdog timer period is 8 seconds.

  I still didn't understand if there is an easy possible to get into a sleep with a routine periods of WD wakings and in the same time enabling a physical interrupt on pin2 that works parallel ?

From my reading of the datasheet, yes, you can use both timers in parallel. But it wasn't clear to me whether a pin-change can both wake the CPU and cause an interrupt (that is, vector into your interrupt routine). A level-interrupt can, if the level is held long enough (I believe they said 4 CPU cycles would be required).


Question about viability of building a Bill Counter machine I have a need for a bill counter at my current job, but besides counting bills we also could use a machine to count admission cards.

The idea is to either buy a bill counter machine (like those that the Banks have), or make one from scratch by buying the parts.
Besides the bill counting feature i wanted to make it so that it also counts the certain number of cards, and check if they are either stamped or not.

My question is:

Is this possible?

If so, is it easier to just buy a arduino and use it with other parts (sensors, moving gears etc etc), or to buy a bill counter and just "crack" the OS?

Any insight would be appreciated!

PS: I am a 1st year Computer Science student, but i have 0 experience in programming in Arduino

There are many more things to consider than just put some parts together if you try to build a counter from scratch. Automated currency handling has come a long way to today's bill counters or any vending machines. You may perfectly handle the computing part of task with an embedded system like the arduino, but paper handling is an art of itself.

If you think of this task as a challenge to acquire and hone engineering skills, go ahead. It may be one of the best training tasks one can think of. But while you may learn a lot from this conundrum, you will propably end up without an usabale device. :)

You have to consider, there are subtasks in

mechanics
electronics
programming

which may include

paper handling (separation, traction, alignment)
pattern recognition
motor control
high speed sensors
signal detection and processing
error and fault processing and handling
motor and gear connection
bearings and mechanical substructure
user interface

and many more.

To modify an existing device solves a lot of mechanical problems in advance. But it may still be difficult to change the firmware of a bill counter to your needs.

You will have to

break into the system (may be impossible)
reverse engineer the firmware
understand the mechanical constraints
find a way to adapt the system to your needs.

A third way, which in my eyes is rather intriguing, is to take an existing bill counter, rip out the controller and try to plug in your own controller, e.g. an arduino. This gives you a real chance to reach your goal while still having the opportunity to learn a lot.


Arduino IO long distance travel I would like to use Arduino to control locks around a building which is 5 storeys high and on every floor there is 2 door.

I'm concerned whether the wires is able to travel all the way from the ground floor to the 5th floor to provide enough power to the relay located at the door.

The lock will be a 12V magnetic lock and it will be unlocked thru a SSR relay which will be controlled by the arduino

Yes, losses in wires are proportional to the length, so an excessively long wire may not be able to deliver enough power. Many factors come into play here:

higher current consumed by the relay increases the losses
smaller wire diameter increses the losses
the voltage required by your relay defines how much you can afford to lose

For example, a pair of AWG23 wires 30m long will have a total resistance of 4 Ohm. If your relay consumes 100 mA, you will lose 0.4V in the wires. If Arduino delivers 5V, and the relay requires a mininum of 4.5V to work, you're just good enough: you're delivering 4.6V to the relay after the losses.


How can I list only files that begin with "/LOG?" Trying to list root directory of LittleFS; but only files beginging with "/LOG."

String str;

                     if (!LittleFS.begin())
                     {
                          Serial.println("LittleFS failed to mount !");
                     }
                     Dir dir = LittleFS.openDir("/");
                     while (dir.next())
                     {

                        if(strncmp(dir.fileName().c_str(), "/LOG", 4) == 0)
                        {

                            str += "";
                            str += dir.fileName();
                            str += "";
                            str += "    ";
                            str += dir.fileSize();
                            str += "
\r\n";
                        }
                     }

                     client.print(str);

If I comment out "if(strncmp(dir.fileName().c_str(), "/LOG", 4) == 0)" and associated braces; all files list.  Code with "if(strncmp(dir.fileName().c_str(), "/LOG", 4) == 0)" no files are listed.

How can I list only files that begin with "/LOG?"

William

Give a filename String to text...

String text = "/LOGsdfsdf";
if(text.startsWith("/LOG")){
//wee file begins with /LOG
}else{
// wops wrong file.
}

Look in here

https://www.arduino.cc/reference/en/language/variables/data-types/stringobject/

Method url startsWith("");

https://www.arduino.cc/reference/en/language/variables/data-types/string/functions/startswith


"Serial" does not name a type -> How to solve this problem? I'm trying my best to solve this problem but it didn't changed

The red line was drawn on the last Serial.println */

int cds = A0;
int led = 12;
int trig1 = 2;      // Left Trig
int trig2 = 3;      // Right Trig
int trig3 = 4;      // Front Trig
int trig4 = 5;      // Upside Trig
int echo1 = 6;      // Left Echo
int echo2 = 7;      // Right Echo
int echo3 = 8;      // Front Echo
int echo4 = 9;      // Upside Echo
int vib1 = 10;      // Left vib
int vib2 = 11;      // Right vib

void setup() {
        pinMode(led, OUTPUT);

        pinMode(trig1, OUTPUT);
        pinMode(trig2, OUTPUT);
        pinMode(trig3, OUTPUT);
        pinMode(trig4, OUTPUT);
        pinMode(echo1, INPUT);
        pinMode(echo2, INPUT);
        pinMode(echo3, INPUT);
        pinMode(echo4, INPUT);
        pinMode(vib1, OUTPUT);
        pinMode(vib2, OUTPUT);

        Serial.begin(9600);
}

void loop(){
  long duration1, value1;
  long duration2, value2;
  long duration3, value3;
  long duration4, value4;

  // Ultra Sonic Sensor Part1
  digitalWrite(trig1,LOW);                           // Trigger Output
  delayMicroseconds(2);
  digitalWrite(trig1,HIGH);
  delayMicroseconds(5);
  digitalWrite(trig1,LOW);
  duration1 = pulseIn(echo1,HIGH);                   // Read Pulse Duration
  value1 = microsecondsToCentimeters(duration1);     // Count Distance
  delay(10);

  // Ultra Sonic Sensor Part2
  digitalWrite(trig2,LOW);
  delayMicroseconds(2);
  digitalWrite(trig2,HIGH);
  delayMicroseconds(5);
  digitalWrite(trig2,LOW);
  duration2 = pulseIn(echo2,HIGH);
  value2 = microsecondsToCentimeters(duration2);
  delay(10);

  // Ultra Sonic Sensor Part3
  digitalWrite(trig3,LOW);
  delayMicroseconds(2);
  digitalWrite(trig3,HIGH);
  delayMicroseconds(5);
  digitalWrite(trig3,LOW);
  duration3 = pulseIn(echo3,HIGH);
  value3 = microsecondsToCentimeters(duration3);
  delay(10);

  // Ultra Sonic Sensor Part4
  digitalWrite(trig4,LOW);
  delayMicroseconds(2);
  digitalWrite(trig4,HIGH);
  delayMicroseconds(5);
  digitalWrite(trig4,LOW);
  duration4 = pulseIn(echo4,HIGH);
  value4 =  microsecondsToCentimeters(duration4);
  delay(10);

  //Commend Part (Vibration motor)

  // Print Out Value
  Serial.print(" dist1 =");
  Serial.print(value1);
  Serial.print("(cm)");
  Serial.print(" dist2 =");
  Serial.print(value2);
  Serial.print("(cm)");
  Serial.print(" dist3 =");
  Serial.print(value3);
  Serial.print("(cm)");
  Serial.print(" dist4 =");
  Serial.print(value4);
  Serial.print("(cm)");
  delay(10);
  //

  // Initialize PIN Mode
  digitalWrite(vib1,HIGH);
  digitalWrite(vib2,HIGH);

  // 진동모터1,2,3
  if (  value4<60  or  value3<60)
  digitalWrite(vib1,LOW);
  digitalWrite(vib2,LOW);

  delay(100);

  digitalWrite(vib1,HIGH);
  digitalWrite(vib2,HIGH);

  if (0< value1 && value1<60)
  digitalWrite(vib1,LOW);

  delay(100);

  digitalWrite(vib1,HIGH);

  if (0< value2 && value2<60)
  digitalWrite(vib1,LOW);

  delay(100);

  digitalWrite(vib1,HIGH);
}

// Function of Count Distance

long microsecondsToCentimeters(long microseconds)
{
  return microseconds/29/2;
}

        int cdsValue = analogRead(cds);

        Serial.print("cds =  ");
        Serial.println(cdsValue);

        if (cdsValue < 38 ) {
                digitalWrite(led, HIGH);
        } else {
                digitalWrite(led, LOW);
        }

Your code would be a lot easier to read and find mistakes in if you formatted it. I see that you did that in the IDE, but in your question, you need to highlight all of the code, then click the "{}" button to make it look like code in your question.

When I pasted your code into my IDE and auto-formatted it, the answer was immediately clear: after the function microsecondsToCentimeters() you have written some code that is not inside any function. C and C++ don't allow that. The error message wasn't very helpful - the compilers easily get confused by our mistakes - but in this case, looking at the formatted code made it clear.

All of the executable code in a C or C++ program (Arduino IDE uses C++) must be inside a typed and named function. Since that is what the compiler was looking for, it seems to have interpreted the word "Serial" as a function type, but no type was defined with that name.

I'm not sure where you intended the lines from the end of long microsecondsToCentimeters() to go, but they need to be inside of a function, somewhere.


MFRC522 minor problems I'm working on a small project for a presentation. My goal is to read the UID of multiple Mifare Classic cards and compare it to a hardcoded list for different actions. All is well (the reading and comparing part that is) but 2 small problems that I have encountered are:

The first (maybe up to three, since the reader is a little bit on the fast side) read after uploading my code will return a UID of just 0s and a wrong PICC type.
After reading a PICC and then trying to read another, the reader prints the UID / PICC Type of the reader before, which is kinda not helpful when trying to light LEDs based on UID.

Here is my sketch:

/*
HEADER TEXT
GOES HERE
*/
#include <SPI.h>
#include <MFRC522.h>
#define SS_PIN 10
#define RST_PIN 9
MFRC522 mfrc522(SS_PIN, RST_PIN);

void setup()
{
  // Serielles Interface initialisieren
  Serial.begin(9600);
  // SPI initialisieren
  SPI.begin();

  mfrc522.PCD_Init();

  // Für später
  // pinMode (2, OUTPUT);
}

void loop()
{
  // Eigene UID bilden. Dazu nehmen wir die 4(7)Byte Hex UID aus Block 0 und quetschen sie in einen schönen String.
  String uID = String(mfrc522.uid.uidByte[0],HEX)+String(mfrc522.uid.uidByte[1],HEX)+String(mfrc522.uid.uidByte[2],HEX)+String(mfrc522.uid.uidByte[3],HEX);

  // PICC Typen
  byte piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);

  // Nach neuen Karten suchen.
  delay(250);
  if ( mfrc522.PICC_IsNewCardPresent())
  {
    delay(250);
    mfrc522.PICC_ReadCardSerial();

    // Debug Ausgabe
    Serial.println();
    Serial.print("Die Kartennummer lautet: ");
    Serial.print(uID);
    Serial.println();
    Serial.print("Picc Type: ");
    Serial.println(mfrc522.PICC_GetTypeName(piccType));
    Serial.println();

    // Überprüfe auf unterstützten PICC Typ und noch mehr Debug Kram
    if ( piccType != MFRC522::PICC_TYPE_MIFARE_MINI && piccType != MFRC522::PICC_TYPE_MIFARE_1K&& piccType != MFRC522::PICC_TYPE_MIFARE_1K) {
      Serial.println("Diese Tech-Demo benötigt MIFARE Classic Karten.");
      return;
    }

    // Den UID String Verglichen und eine entsprechende Aktion ausführen
    if(uID=="myUIDforStuff") {
      Serial.println("Access granted");
    }
  }
}

/*
HEADER TEXT
GOES HERE
*/
#include <SPI.h>
#include <MFRC522.h>
#define SS_PIN 10
#define RST_PIN 9
MFRC522 mfrc522(SS_PIN, RST_PIN);

void setup()
{
  // Serielles Interface initialisieren
  Serial.begin(9600);
  // SPI initialisieren
  SPI.begin();

  mfrc522.PCD_Init();

  // Für später
  // pinMode (2, OUTPUT);
}

void loop()
{
  // Eigene UID bilden. Dazu nehmen wir die 4(7)Byte Hex UID aus Block 0 und quetschen sie in einen schönen String.
// String uID = String(mfrc522.uid.uidByte[0],HEX)+String(mfrc522.uid.uidByte[1],HEX)+String(mfrc522.uid.uidByte[2],HEX)+String(mfrc522.uid.uidByte[3],HEX);

  // PICC Typen
// byte piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);

  // Nach neuen Karten suchen.
  delay(250);
  if ( mfrc522.PICC_IsNewCardPresent())
  {
    delay(250);
    mfrc522.PICC_ReadCardSerial();
     // Eigene UID bilden. Dazu nehmen wir die 4(7)Byte Hex UID aus Block 0 und quetschen sie in einen schönen String.
 String uID = String(mfrc522.uid.uidByte[0],HEX)+String(mfrc522.uid.uidByte[1],HEX)+String(mfrc522.uid.uidByte[2],HEX)+String(mfrc522.uid.uidByte[3],HEX);

  // PICC Typen
 byte piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);

    // Debug Ausgabe
    Serial.println();
    Serial.print("Die Kartennummer lautet: ");
    Serial.print(uID);
    Serial.println();
    Serial.print("Picc Type: ");
    Serial.println(mfrc522.PICC_GetTypeName(piccType));
    Serial.println();

    // Überprüfe auf unterstützten PICC Typ und noch mehr Debug Kram
    if ( piccType != MFRC522::PICC_TYPE_MIFARE_MINI && piccType != MFRC522::PICC_TYPE_MIFARE_1K&& piccType != MFRC522::PICC_TYPE_MIFARE_1K) {
      Serial.println("Diese Tech-Demo benötigt MIFARE Classic Karten.");
      return;
    }

    // Den UID String Verglichen und eine entsprechende Aktion ausführen
    if(uID=="myUIDforStuff") {
      Serial.println("Access granted");
    }
  }
}