text:
LED Matrix Display with dissimilar brightness
So far I have seen in LED matrix related projects that the brightness is controlled in an entirety manner. That means the   brightness of total display can either be reduced or increased. How can we display only a part of the display with more brighter than the remaining matrix? Appreciate if anyone provide some pseudo logic to achieve this.

Let us say the matrix is made of simple grid of LEDs (monochrome) and to control the display using multiplexing technique by shift registers. I agree that the brightness can be controlled by duty cycle if it is a single one. My question is how to achieve dissimilar brightness in a grid LED matrix by PWM/duty cycle methods. For example, if I want to display time in HH:MM pattern in which the HH part of the display to be more brighter than MM part.

There's two options:

Use a matrix driver that supports different brightnesses per pixel, or:
Rapidly display a different arrangement of pixels in quick succession. The pixels that are on more often are brighter.

Option 1 basically does option 2 in hardware.
The theory is simple:  For one LED you can vary the brightness by using PWM - that switches the LED on and off very rapidly. The longer it is on the brighter it appears.
You can do the same with a matrix of pixels. Instead of dealing with one pixel though you are dealing with, in effect, a series of "images". Each "image" has a different combination of pixels. The more "images" you have the greater variation you can get in your pixel brightnesses.
For example if you first display a frame of:
. . . . . . . .
. . # # # # . .
. # . . . . # .
. # . . . . # .
. # . . . . # .
. # . . . . # .
. . # # # # . .
. . . . . . . .

followed by the image:
. . . . . . . #
. . # # # # # .
. # . . . # # .
. # . . # . # .
. # . # . . # .
. # # . . . # .
. # # # # # . .
# . . . . . . .

then you will get a bright circle(ish) shape with a dimmer slash through it.
The only problem with this method is flicker. You have to have your matrix refreshing very fast. The more "images" you have to display in sequence the more it will flicker and the faster you will have to refresh your matrix to compensate.

Short answer: You likely can't, at a hardware level.
The only way you'd be able to do this is to vary the duty cycle of each individual LED in the matrix (the percent of on-time vs. off-time).
The device would have to support that. Edit your question with the model number of the LED matrix you're using and it's spec sheet.
(Note that if you're using a simple grid of LEDs and row/column addressing you could use PWM to get some control over brightness, but you'd probably already be using multiplexing of the LEDs, which makes varying brightness per LED more complex.)

LED brightness is normally controlled by how long a given LED is lit.  An LED that is on for 70ms and off for 30ms will be brighter then an LED that is on for only 30ms and off for 70ms.
So, the answer is to shorten the amount of time which the LED is on and lethen the time the LED is off for only those LEDs in your display which are to be dimmer.
This is usually referred to as the duty cycle of the LED.  On an Arduino, the PWM or Pulse Width Modulator feature of the embedded processor is normally used to create the duty cycle signal for an LED.

Depends on what LEDs your matrix is made of. One option would be to make it from 'smart' LEDs at each location, such as WS2812B. These are a chip and 3 LEDs in one package, usually a 5050 size SMD package, but they can also be had in thru hole packages, and can be found built up into boards also (look at Sparkfun and Adfruit for examples). Serial data is sent in, with a 0-255 value for each LED, the control chip then drives the 3 LEDs with the PWM level commanded - 0/255 for off, 128/255 for 1/2 on for example, 255/255 for full on.  The data is passed from device to device to load them up, so for example an 8x8 matrix would need 8x8x3 = 192 bytes of data sent in to load the display. The Arduino then doesn't need to do any more until the matrix needs to change.  WS2812B needs some fancy timing to send in 0/1 data in a combined data/clock signal line, options are the Neopixel library or the FastLed.h library for Arduino, to send data in at up to 800 KHz rate. There is also another version of the chip that uses seperate clock and data lines, SPI.transfer I think can be used to send in data even faster.  I don't recall that device's part number off hand, I've not used it.
For premade 8x8 modules using single color LEDs, then as described in other answers  MAX7219 is often used, with 15 levels of brightness available for the whole display.


text:
Suitable long-term sensors for PM, Ozone and NO2
I am totally new to Arduino. I have a Arduino Mega 2560 and I would like to perform long-term observations of PM, Ozone and NO2 (for around a year, outdoors).
Do you have any ideas which sensors might be suitable for this? I have a few sensors in mind (SDS011, Plantower PMS 1003, Sharp GP2Y1010AU0F, Honeywell HPMA115S0...) but since this is my first time doing this kind of stuff, I dont have any experience.

This sounds like more of an electronics/sensors question than an Arduino question. I'd say first identify the sensor(s) that meet your needs, and then figure out how to interface them with your Arduino.

Thanks! Since I have no experience at all with this, I wanted to asked experienced users, which sensors may fit my needs. Where can I ask this, if not here?

The electronics stack exchange would be a good place to start.

Explain your needs (weatherproof, able to be interfaced with and Arduino microcontroller easily, will last > 1 year without adjustment, etc)

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
error cannot convert string TO uint_8t
this is the code i am working on for controlling leds
#include <WiFi.h>                                                // esp32 library
#include <IOXhop_FirebaseESP32.h>                                             // firebase library
#define FIREBASE_HOST "mmmmm"                         // the project name address from firebase id
#define FIREBASE_AUTH "mmmmmmm"                    // the secret key generated from firebase
#define WIFI_SSID "mmmmm"                                          // input your home or public wifi name
#define WIFI_PASSWORD "mmmmmm"                                    //password of wifi ssid

String fireStatus ;
String fireStatus1 ;
String fireStatus3 ;
String fireStatus4 ; // led status received from firebase
int relay1 = 15;
int relay2 = 2;
int relay3 = 4;
int relay4 = 5;

void setup() {

Serial.begin(115200);

pinMode(15, OUTPUT);
pinMode(2, OUTPUT);
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);                                      //try to connect with wifi
Serial.print("Connecting to ");
Serial.print(WIFI_SSID);
  while (WiFi.status() != WL_CONNECTED) {
      Serial.print(".");
    delay(300);
  }
  Serial.println();
  Serial.print("Connected to ");
  Serial.println(WIFI_SSID);
  Serial.print("IP Address is : ");
  Serial.println(WiFi.localIP());                                                      //print local IP address
  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);                                       // connect to firebase

}
void loop() {

  {
    fireStatus =  Firebase.getString("S1");

    Serial.println("Switch1 Turned ON/OFF");
    digitalWrite(15,fireStatus );
    fireStatus1 =  Firebase.getString("S2");
     Serial.println("Switch2 Turned ON/OFF");
    digitalWrite(2,fireStatus1 );

     fireStatus3 =  Firebase.getString("S3");
     Serial.println("Switch3 Turned ON/OFF");
    digitalWrite(4,fireStatus3));

     fireStatus4 =  Firebase.getString("S4");

     Serial.println("Switch4 Turned ON/OFF");
    digitalWrite(5,fireStatus4 );

}
}

You should always provide the full error message including the line, where the error occurred

You cannot directly cast a String to an uint8 for use with digitalWrite(). What string do you get from Firebase?

fireStatus.toInt() or Firebase.getInt("S1")?

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Stuck making multi, many button, joysticks
I'm stuck, I figured I'd ask here for some help... Note I'm a newb and this is essentially my first Arduino project beyond blink...
I'm creating Virtual cockpit panels for DCS World, using an Arduino Leonardo as an HID device. I'm using three SN74HC165 Shift-In registers for multi-buttons (24) - as it seemed the easiest - and all in all it does work...
So I figured that I'm using only 4 pins on the Leonardo, so why not try to setup 3 of these "shift-in clusters" (12 pins) to appear as 3 separate joysticks?
I got the one working and I got 2 more joysticks showing up in Windows10... now my problem is: how would I setup 2 more "shiftIn Clusters", I've tried many things but I must defer to outside help (cause I really don't know what I'm doing)
Edit to clarify: So each joystick need 3 or 4 shift registers making 24-32 buttons on each joystick
Shift In Lib: https://github.com/…/Ardu…/blob/master/ShiftIn/src/ShiftIn.h
Joy2 Lib: https://github.com/MHeironimus/ArduinoJoystickLibrary
Here's an image of the Layout I want: https://i.stack.imgur.com/sEtRp.png
... any help would relieve a great headache, Thank for your time
#include <ShiftIn.h>
#include <Joystick.h>

// use <n> shift registers
ShiftIn<3> shift;             // use three shift register

// Create joystick
// TESTING MULTI JOYSTICKS
// 1/3 Works!!!
// 3/3 Appear in Windows
// ????? must add shiftIn sections for 2nd and 3rd joysticks????
// (add pin usage + modify line 77-79 stuff)

#define JOYSTICK_COUNT 3
Joystick_ Joystick[JOYSTICK_COUNT] = {
  Joystick_(0x03, JOYSTICK_TYPE_GAMEPAD, 32, 0, false, false, false, false, false, false, false, false, false, false, false),
  Joystick_(0x04, JOYSTICK_TYPE_GAMEPAD, 32, 0, false, false, false, false, false, false, false, false, false, false, false),
  Joystick_(0x05, JOYSTICK_TYPE_GAMEPAD, 32, 0, false, false, false, false, false, false, false, false, false, false, false),
};

// Set to true to test "Auto Send" mode or false to test "Manual Send" mode.
//const bool testAutoSendMode = true;
const bool testAutoSendMode = false;

const unsigned long gcCycleDelta = 1000;
const unsigned long gcAnalogDelta = 25;
const unsigned long gcButtonDelta = 500;
unsigned long gNextTime = 0;
unsigned int gCurrentStep = 0;
int gJoystickId = 0;

/*
// WORKING SECTION Single Joystick with Shift Reg
Joystick_ Joystick(JOYSTICK_DEFAULT_REPORT_ID, JOYSTICK_TYPE_GAMEPAD,
  32, 0,                        // Button Count, Hat Switch Count
  false, false, false,          // X and Y, but no Z Axis
  false, false, false,          // No Rx, Ry, or Rz
  false, false,                 // No rudder or throttle
  false, false, false);         // No accelerator, brake, or steering
*/

void setup() {

  shift.begin(8, 9, 11, 12);  // set pins of the shift register
//  shift[1].begin(7, 6, 5, 4);  // set pins of the shift register
//  shift[2].begin(3, 2, 1, 0);  // set pins of the shift register

 Joystick[0].begin();
 Joystick[1].begin();
 Joystick[2].begin();
}

void loop() {

  if (shift.update()) {
    for (int i = 0; i < shift.getDataWidth(); i++)
    Joystick[0].setButton(i, shift.state(i));            // just press or release the button
  }
/*if (shift[1].update()) {
    for (int i = 0; i < shift[1].getDataWidth(); i++)
    Joystick[0].setButton(i, shift[1].state(i));            // just press or release the button
  }
if (shift[2].update()) {
    for (int i = 0; i < shift[2].getDataWidth(); i++)
    Joystick[0].setButton(i, shift[2].state(i));            // just press or release the button
  }
  delay(10);
*/
}

Each ShiftIn instance handles just one connection. You need to make multiple instances.
ShiftIn shift1<3>;
ShiftIn shift2<3>;
ShiftIn shift3<3>;

Then you begin each of them:
void setup() {
    shift1.begin(8, 9, 11, 12);
    shift2.begin(7, 6, 5, 4);
    shift3.begin(3, 2, 1, 0);
    ... etc ...
}

Each shiftx is a completely separate entity. You can just repeat your block of code for each shift object:
if (shift1.update()) {
    for (int i = 0; i < shift1.getDataWidth(); i++)
    Joystick[0].setButton(i, shift1.state(i));
}

if (shift2.update()) {
    for (int i = 0; i < shift2.getDataWidth(); i++)
    Joystick[1].setButton(i, shift2.state(i));
}

if (shift3.update()) {
    for (int i = 0; i < shift3.getDataWidth(); i++)
    Joystick[2].setButton(i, shift3.state(i));
}

You could arrange the ShiftIn objects into an array like you do with your Joystick objects and then loop through them, but that is pretty pointless for just three of them.

Thanks for your reply!
I didn't make my question clear, I need at least 24 buttons on each joystick so 3 shift registers on each joystick.. I added a picture

@FedaykinWolf Ah right. I misunderstood. I'll modify my answer.

That was it!!! the first part I din't understand how to start 3 instances (Also I was trying to modify "ShiftIn" and not "Shift"...
Thank you soo much! suddenly my headache is cured.

@FedaykinWolf Another option to save wiring is to connect all of them together to make one ShiftIn shift<9>; and do how I had before.

Thanks again! I was thinking about that option, but I need it a little more modular so I can change cockpit types (F-16, F-18, A-10) quickly, and easily


text:
Controlling 16x2 LCD backlight (I2C module)
I've installed an I2C module on my 16x2 LCD so i don't have access to all those LCD pins to control the backlight LED.
BUT there is a 100 ohm smd resistor in series with anode of the backlight LED, i want to remove the resistor and use Arduino PWM to control the backlight or i can just replace that resistor with a 330 ohm or a 1K resistor.

Red box showing the resistor and blue box showing the Jumper.
Also I2C module itself have a jumper for LED backlight which also goes to that resistor...
Just wanted to ask here and make sure it is going to work before doing any modification to the LCD.
which way is better? is it going to work?

UPDATE: i used Arduino PWM and a 2n2222 transistor and was able to successfully control the backlight brightness via jumper pins of I2C module.

Possibly. Do you have a schematic of the I2C module?

@Majenko this is the datasheet i found

not sure why i got a down vote...

Probably because you were very vague.

@Majenko or maybe people really want to finish that down vote achievement ;)

It's hard to tell from that datasheet what backlight control there is. It looks like it's connected to pin 3 of the IO expander, and that 100Ω resistor you speak of is inline. What the back light jumper does I have no idea. In all probability you can remove the jumper, then one pin of it will connect to the anode of the back light for you to connect to wherever you want to drive it from.

@Majenko thanks man i'll try that, gonna delete this question because of that down vote!

Don't. I just cancelled it with an upvote.

@Majenko you're so nice, thanks again.

It's hard to tell from the limited information, but chances are the "backlight jumper" mentioned in passing in the datasheet can be simply removed.  This will then give you two pins.  One will connect to pin 3 of the IO expander, and the other will connect to the back light anode itself.
Which is which you will have to discover for yourself.  One of them will have the 100Ω resistor in line with it as well.
If you can't see the tracks (some black boards are hard to make them out) then you should get a digital multimeter and set it to continuity mode and probe the pins to see where they lead.
Once you have identified which pin is which you can connect the one that goes to the back light to your Arduino and drive it with PWM.


text:
Post Data Server from Arduino using Fuzzy Logic
Can somebody help me , when i run this code separately , no problem was found , but when i fuse it together , only fuzzy work and the data can't be sent to my server, sorry for my bad english
i already tried to separate them with function and give delay to make time for posting data , but maybe that not the real problem
#include "SoftwareSerial.h"
#include <dht.h>
#include <Fuzzy.h>
#define DEBUG true
#define dht_apin A1 // Analog Pin sensor is connected to
SoftwareSerial esp(6, 7);// RX, TX
String ssid = "BU SIS";
String password = "Bismillah";
dht DHT;
// Fuzzy
Fuzzy *fuzzy = new Fuzzy();
// FuzzyInputKudara
FuzzySet *urendah = new FuzzySet(0, 50, 50, 50);
FuzzySet *usedang = new FuzzySet(45, 60, 60, 75);
FuzzySet *utinggi = new FuzzySet(70, 70, 100, 100);
// FuzzyInputKtanah
FuzzySet *trendah = new FuzzySet(0, 50, 50, 50);
FuzzySet *tsedang = new FuzzySet(45, 60, 60, 75);
FuzzySet *ttinggi = new FuzzySet(70, 70, 100, 100);
// FuzzyInputSudara
FuzzySet *srendah = new FuzzySet(20, 27, 27, 31);
FuzzySet *stinggi = new FuzzySet(30, 35, 40, 40);
// FuzzyOutputKondisi
FuzzySet *tidak = new FuzzySet(0, 25, 25, 50);
FuzzySet *siram = new FuzzySet(50, 80, 100, 100);
String data;
String server = "192.168.100.11";
String uri = "/web/insertx.php";
String temp , hum;
int ftemp, fhum;
int tanah;
void setup() {
  Serial.begin(9600);
  esp.begin(9600);
  // Reset modul
  sendCommand("AT+RST\r\n", 1000, DEBUG);
  // Konfigurasikan sebagai Akses poin & Wifi
  sendCommand("AT+CWMODE=3\r\n", 1000, DEBUG);
  // Sesuaikan dengan SSID dan Password
  sendCommand("AT+CWJAP=\"BU SIS\",\"Bismillah\"\r\n", 10000, DEBUG);
  // Mendapatkan IP adress
  sendCommand("AT+CIFSR\r\n", 1000, DEBUG);
  // Konfigurasikan untuk multiple connection
  sendCommand("AT+CIPMUX=1\r\n", 1000, DEBUG);
    //   FuzzyInput
    FuzzyInput *kudara = new FuzzyInput(1);
    kudara->addFuzzySet(urendah);
    kudara->addFuzzySet(usedang);
    kudara->addFuzzySet(utinggi);
    fuzzy->addFuzzyInput(kudara);
    // FuzzyInput
    FuzzyInput *ktanah = new FuzzyInput(2);
    ktanah->addFuzzySet(trendah);
    ktanah->addFuzzySet(tsedang);
    ktanah->addFuzzySet(ttinggi);
    fuzzy->addFuzzyInput(ktanah);
    // FuzzyInput
    FuzzyInput *sudara = new FuzzyInput(3);
    sudara->addFuzzySet(srendah);
    sudara->addFuzzySet(stinggi);
    fuzzy->addFuzzyInput(sudara);
    // FuzzyOutput
    FuzzyOutput *kondisi = new FuzzyOutput(1);
    kondisi->addFuzzySet(tidak);
    kondisi->addFuzzySet(siram);
    fuzzy->addFuzzyOutput(kondisi);
    // Building FuzzyRule 3
    FuzzyRuleAntecedent *a3 = new FuzzyRuleAntecedent();
    a3->joinWithAND(urendah, tsedang);
    FuzzyRuleAntecedent *ktanah3 = new FuzzyRuleAntecedent();
    ktanah3->joinSingle(srendah);
    FuzzyRuleAntecedent *aa3 = new FuzzyRuleAntecedent();
    aa3->joinWithAND(a3, ktanah3);
    FuzzyRuleConsequent *maka3 = new FuzzyRuleConsequent();
    maka3->addOutput(siram);
    FuzzyRule *fuzzyRule3 = new FuzzyRule(3, aa3, maka3);
    fuzzy->addFuzzyRule(fuzzyRule3);
    // Building FuzzyRule 5
    FuzzyRuleAntecedent *a5 = new FuzzyRuleAntecedent();
    a5->joinWithAND(urendah, ttinggi);
    FuzzyRuleAntecedent *ktanah5 = new FuzzyRuleAntecedent();
    ktanah5->joinSingle(srendah);
    FuzzyRuleAntecedent *aa5 = new FuzzyRuleAntecedent();
    aa5->joinWithAND(a5, ktanah5);
    FuzzyRuleConsequent *maka5 = new FuzzyRuleConsequent();
    maka5->addOutput(siram);
    FuzzyRule *fuzzyRule5 = new FuzzyRule(5, aa5, maka5);
    fuzzy->addFuzzyRule(fuzzyRule5);
    // Building FuzzyRule 9
    FuzzyRuleAntecedent *a9 = new FuzzyRuleAntecedent();
    a9->joinWithAND(usedang, tsedang);
    FuzzyRuleAntecedent *ktanah9 = new FuzzyRuleAntecedent();
    ktanah9->joinSingle(srendah);
    FuzzyRuleAntecedent *aa9 = new FuzzyRuleAntecedent();
    aa9->joinWithAND(a9, ktanah9);
    FuzzyRuleConsequent *maka9 = new FuzzyRuleConsequent();
    maka9->addOutput(siram);
    FuzzyRule *fuzzyRule9 = new FuzzyRule(9, aa9, maka9);
    fuzzy->addFuzzyRule(fuzzyRule9);
    //   Building FuzzyRule 11
    FuzzyRuleAntecedent *a11 = new FuzzyRuleAntecedent();
    a11->joinWithAND(usedang, ttinggi);
    FuzzyRuleAntecedent *ktanaha11 = new FuzzyRuleAntecedent();
    ktanaha11->joinSingle(srendah);
    FuzzyRuleAntecedent *aa11 = new FuzzyRuleAntecedent();
    aa11->joinWithAND(a11, ktanaha11);
    FuzzyRuleConsequent *maka11 = new FuzzyRuleConsequent();
    maka11->addOutput(siram);
    FuzzyRule *fuzzyRule11 = new FuzzyRule(11, aa11, maka11);
    fuzzy->addFuzzyRule(fuzzyRule11);
    // Building FuzzyRule 12
    FuzzyRuleAntecedent *a12 = new FuzzyRuleAntecedent();
    a12->joinWithAND(usedang, stinggi);
    FuzzyRuleAntecedent *ktanaha2 = new FuzzyRuleAntecedent();
    ktanaha2->joinSingle(ttinggi);
    FuzzyRuleAntecedent *aa12 = new FuzzyRuleAntecedent();
    aa12->joinWithAND(a12, ktanaha2);
    FuzzyRuleConsequent *makaa2 = new FuzzyRuleConsequent();
    makaa2->addOutput(siram);
    FuzzyRule *fuzzyRule12 = new FuzzyRule(12, aa12, makaa2);
    fuzzy->addFuzzyRule(fuzzyRule12);
    // Building FuzzyRule 15
    FuzzyRuleAntecedent *a15 = new FuzzyRuleAntecedent();
    a15->joinWithAND(utinggi, srendah);
    FuzzyRuleAntecedent *ktanaha5 = new FuzzyRuleAntecedent();
    ktanaha5->joinSingle(tsedang);
    FuzzyRuleAntecedent *aa15 = new FuzzyRuleAntecedent();
    aa15->joinWithAND(a15, ktanaha5);
    FuzzyRuleConsequent *makaa5 = new FuzzyRuleConsequent();
    makaa5->addOutput(siram);
    FuzzyRule *fuzzyRule15 = new FuzzyRule(15, aa15, makaa5);
    fuzzy->addFuzzyRule(fuzzyRule15);
    // Building FuzzyRule 17
    FuzzyRuleAntecedent *a17 = new FuzzyRuleAntecedent();
    a17->joinWithAND(utinggi, ttinggi);
    FuzzyRuleAntecedent *ktanaha7 = new FuzzyRuleAntecedent();
    ktanaha7->joinSingle(srendah);
    FuzzyRuleAntecedent *aa17 = new FuzzyRuleAntecedent();
    aa17->joinWithAND(a17, ktanaha7);
    FuzzyRuleConsequent *makaa7 = new FuzzyRuleConsequent();
    makaa7->addOutput(siram);
    FuzzyRule *fuzzyRule17 = new FuzzyRule(17, aa17, makaa7);
    fuzzy->addFuzzyRule(fuzzyRule17);
  delay(10000);
}
void dataku() {
  DHT.read11(dht_apin);
  fhum = DHT.humidity;
  ftemp = DHT.temperature;
  tanah = analogRead(A0);
  tanah = map(tanah, 1023, 36, 100, 0);
  hum = String(fhum);
  temp = String(ftemp);
  fuzzy->setInput(1, fhum);
  fuzzy->setInput(2, tanah);
  fuzzy->setInput(3, ftemp);
  fuzzy->fuzzify();
  Serial.println(fhum);
  Serial.println(ftemp);
  Serial.println(tanah);
  Serial.print("\n\nKondisi: ");
  if (siram->getPertinence() > tidak->getPertinence()) {
    Serial.println("Siram\n");
    pinMode(10, OUTPUT);
    digitalWrite(10, LOW);
  } else {
    Serial.println("Tidak Siram\n");
    pinMode(10, OUTPUT);
    digitalWrite(10, HIGH);
  };
  float output1 = fuzzy->defuzzify(1);
  data = "suhu=" + temp + " & udara=" + hum + " & tanah=" + tanah;// data sent must be under this form //name1=value1&name2=value2.
//    data = "suhu=10 & udara=20 & tanah=30";
  Serial.println(data);
}
void loop() {
  esp.println("AT+CIPSTART=0,\"TCP\",\"" + server + "\",80");//start a TCP connection.
  if ( esp.find("OK")) {
    Serial.println("Koneksi siap");
  };
  Serial.println("=>======================================");
  dataku();
  httppost();
  delay(5000);
}
void httppost () {
  String postRequest =
    "POST " + uri + " HTTP/1.1\r\n" +
    "Host: " + server + "\r\n" +
    "Connection: close\r\n" +
    "Content-Type: application/x-www-form-urlencoded\r\n" +
    //    "Content-Type: application/json;charset=UTF-8\r\n"+
    "Content-Length: " + data.length() + "\r\n" +
    "\r\n" + data;
  String sendCmd = "AT+CIPSEND=0";//determine the number of caracters to be sent.
  //Serial.println(postRequest);
  esp.print(sendCmd);
  esp.print(",");
  esp.println(postRequest.length());
  delay(200);
  if (esp.find(">")) {
    Serial.println("Sending.."); esp.print(postRequest);
    if ( esp.find("SEND OK")) {
      Serial.println("Packet sent");
      while (esp.available()) {
        String tmpResp = esp.readString();
        Serial.println(tmpResp);
      }
      // close the connection
      delay(3000);
      esp.println("AT+CIPCLOSE");
      Serial.println("PUTUS");
    }
    //    Serial.println(postRequest);
  }
  delay(4000);
  //  Serial.println(sendCmd + postRequest.length() );
}

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

Sketch uses 17524 bytes (54%) of program storage space. Maximum is 32256 bytes. Global variables use 832 bytes (40%) of dynamic memory, leaving 1216 bytes for local variables. Maximum is 2048 bytes.

Hint: Measure free memory after setup() i.e. call freeMemory() and print last in setup. https://learn.adafruit.com/memories-of-an-arduino/measuring-free-memory

06:39:14.727 -> AT+RST
06:39:14.727 -> busy p...
06:39:15.745 -> AT+CWMODE=3
06:39:15.745 -> busy p...
06:39:25.809 -> AT+CWJAP="BU SIS","Bismillah"
06:39:25.844 -> busy p...
06:39:25.844 -> OK
06:39:26.825 -> AT+CIFSR
06:39:26.825 -> 192.168.4.1
06:39:26.858 -> 192.168.100.30
06:39:26.858 -> OK
06:39:27.846 -> AT+CIPMUX=1
06:39:27.879 -> OK
06:39:27.879 -> 238
06:39:37.850 -> 238
06:39:38.019 -> Koneksi siap
06:39:38.019 -> =>======================================

06:39:38.053 -> 69
06:39:38.053 -> 28
06:39:38.087 -> 96
06:39:38.087 ->
06:39:38.087 ->
06:39:38.087 -> Kondisi: Siram
06:39:38.087 ->
06:39:38.087 -> 186
06:39:38.087 -> 96
06:39:38.123 -> 181
06:39:38.295 -> Sending..
06:39:48.283 -> 181
06:39:49.297 -> =>======================================
06:39:49.331 -> 71
06:39:49.331 -> 28
06:39:49.365 -> 96

did it means , my arduino can't handle that code together ?

The Arduino Uno has only 2K byte. That is one million times smaller than todays PCs. It is important to understand memory allocation and how to write code that does not consume as much memory. My guess was that you are very close to the limit and need to rewrite some sections to reduce the memory footprint. But first of all it is important to understand how much memory is used and where in the code.


text:
I cannot open/write to dataFile SD shield in mySketch but have no problem with Datalogger example sketch from the SD library...?
Hello Arduino Community
I am collecting data and attempting to log it on to a Deek Robot SD shield via a Mega.
I have the data  in a dataString which I can Serial.print to the monitor but would like to log it to an SD card instead. When I run the the Datalogger example sketch from the SD library I can see the data and access the datalog file from the SD card (as per point of the example) but when I try to cross-pollinate the example with mySketch the debugging message

error opening datalog.txt

is all I get.
I've uploaded the sketch, apologies it is pretty long, there's some adc stuff going on, the call for the data file open and write etc starts on line 200 and ends on 212.
I've tried positioning the datafile functions in different places in the code, using other libraries, reading forum posts but I am getting nowhere. if anyone could point out what I'm doing wrong I would be eternally grateful.
Cheers,
Michael

//!!!change this to name of sketch!!!!
#define SKETCH_VERSION "SD for loop array test"

//include relevant libraries
#include <EnableInterrupt.h>
#include <SPI.h>
#include <SD.h>

//globally define pins
#define BUSY 3    //purple*
#define RD 4      //yellow* RD+CS tied together
#define RESET 5   //grey*
#define CONVST 6  //green* CONVSTA+CONVSTB soldered together on the board
#define RANGE 7   //blue*   *not permanent - double check!!!*

#define DB0 38
#define DB1 39
#define DB2 40
#define DB3 41
#define DB4 42
#define DB5 43
#define DB6 44
#define DB7 45
#define DB8 46
#define DB9 47
#define DB10 48
#define DB11 49
#define DB12 50
#define DB13 51
#define DB14 52
#define DB15 53

byte statusLed       = 13;
byte sensorPin1       = 10;
byte sensorPin2       = 11;
byte sensorPin3       = 12;

int sensorValue[8];
int rawData[16];

//change the size  of these arrays to match the amount of channels being read by the ADC
int adcChannel[5];
int adcData[5];
int channelCount=5;

volatile byte pulseCount1;
volatile byte pulseCount2;
volatile byte pulseCount3;

int pulses[3];

// cs pin for sd-shield *NB 53 for Mega
const int chipSelect = 53;

unsigned long oldTime;

void setup() {             //set up the hardware

  Serial.begin(9600);
  //sd card.....
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.print("Initializing SD card...");

  // see if the card is present and can be initialized:
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    // don't do anything more:
    while (1);
  }
  Serial.println("card initialized.");

  enableInterrupt(BUSY, bitBang, FALLING);

  oldTime            = 0;

  pinMode(DB0, INPUT_PULLUP);
  pinMode(DB1, INPUT_PULLUP);
  pinMode(DB2, INPUT_PULLUP);
  pinMode(DB3, INPUT_PULLUP);
  pinMode(DB4, INPUT_PULLUP);
  pinMode(DB5, INPUT_PULLUP);
  pinMode(DB6, INPUT_PULLUP);
  pinMode(DB7, INPUT_PULLUP);
  pinMode(DB8, INPUT_PULLUP);
  pinMode(DB9, INPUT_PULLUP);
  pinMode(DB10, INPUT_PULLUP);
  pinMode(DB11, INPUT_PULLUP);
  pinMode(DB12, INPUT_PULLUP);
  pinMode(DB13, INPUT_PULLUP);
  pinMode(DB14, INPUT_PULLUP);
  pinMode(DB15, INPUT_PULLUP);

  pinMode(RESET, OUTPUT);
  pinMode(CONVST, OUTPUT);
  pinMode(RD, OUTPUT);
  pinMode(RANGE, OUTPUT);
  pinMode(BUSY, INPUT);

  //reset ADC to begin conversion
  digitalWrite(RESET, HIGH);
  delayMicroseconds(10);
  digitalWrite(RESET, LOW);

  digitalWrite(CONVST, LOW);
  digitalWrite(RD, HIGH);
  digitalWrite(RANGE, LOW);
  digitalWrite(BUSY, LOW);

  delayMicroseconds(100);

  // Set up the status LED line as an output
  pinMode(statusLed, OUTPUT);
  digitalWrite(statusLed, HIGH);  // We have an active-low LED attached

  pinMode(sensorPin1, INPUT);
  digitalWrite(sensorPin1, HIGH);

  pinMode(sensorPin2, INPUT_PULLUP);
  digitalWrite(sensorPin2, HIGH);

  pinMode(sensorPin3, INPUT_PULLUP);
  digitalWrite(sensorPin3, HIGH);

  pulseCount1        = 0;
  pulseCount2        = 0;
  pulseCount3        = 0;

  oldTime            = 0;

  // the hall effect sensors are configured to trigger on a FALLING state change
  // (transition from HIGH state to LOW state)
  enableInterrupt(sensorPin1, pulseCounter1, FALLING);
  enableInterrupt(sensorPin2, pulseCounter2, FALLING);
  enableInterrupt(sensorPin3, pulseCounter3, FALLING);

  //this prints the name of the sketch !!!read line 1!!!
  Serial.print("sketch version: ");
  Serial.println(SKETCH_VERSION);

}

void loop() {
  //Serial.print("hello");
  //change this value to preferred sampling rate
  if ((millis() - oldTime) == 1000) {

    oldTime = millis();

    //Serial.print(millis());
    //Serial.print("\t");

    //tell ADC to start read (converting analogue input to digital output)
    delayMicroseconds(10);
    digitalWrite(CONVST, LOW);
    delayMicroseconds(10);
    digitalWrite(CONVST, HIGH);
    //when read-conversion is complete ADC sends the BUSY pin low triggering the bitBang ISR

    //print ADC data from array within the bitBang ISR to a string
    String adcString = "";
    for(int thisChannel=0; thisChannel<channelCount; thisChannel++){
      adcString += String(adcData[thisChannel]);
      adcString += ",";
    }

    //disable interrupt to access current pulse count
    disableInterrupt(sensorPin1);
    disableInterrupt(sensorPin2);
    disableInterrupt(sensorPin3);
    //grab current pulse count and store in a variable
    pulses[0] = pulseCount1;
    pulses[1] = pulseCount2;
    pulses[2] = pulseCount3;
    //reset pulse count
    pulseCount1 = 0;
    pulseCount2 = 0;
    pulseCount3 = 0;
    //enable interrupt and start incrementing pulse count again
    enableInterrupt(sensorPin1, pulseCounter1, FALLING);
    enableInterrupt(sensorPin2, pulseCounter2, FALLING);
    enableInterrupt(sensorPin3, pulseCounter3, FALLING);

    String pulseString = "";
    for(int i=0; i<3; i++){
      pulseString += String(pulses[i]);
      if (i<2) {
        pulseString += ",";
      }
    }

    String dataString = String(adcString + pulseString);
  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
  File dataFile = SD.open("datalog.txt", FILE_WRITE);

  // if the file is available, write to it:
  if (dataFile) {
    dataFile.println(dataString);
    dataFile.close();
    // print to the serial port too:
    Serial.println(dataString);
  }
  // if the file isn't open, pop up an error:
  else {
    Serial.println("error opening datalog.txt");
  }

 //Serial.println(dataString);

  }
//start again
}

//grabbing ADC data ISR (for n channel)
void bitBang ()  {
  //a for loop to bitbang the values fom the analogue (ADC) channels (maximum 8) sequentially storing them in a variable array (equal to the channels of the ADC)
  for(int thisChannel=0; thisChannel<channelCount; thisChannel++){
  //send ADC read pin low to bitbang the first channel
  digitalWrite(RD, LOW);
  //read the state of the 16 pins and store in a variable
  rawData[0] = digitalRead(DB15);
  rawData[1] = digitalRead(DB14);
  rawData[2] = digitalRead(DB13);
  rawData[3] = digitalRead(DB12);
  rawData[4] = digitalRead(DB11);
  rawData[5] = digitalRead(DB10);
  rawData[6] = digitalRead(DB9);
  rawData[7] = digitalRead(DB8);
  rawData[8] = digitalRead(DB7);
  rawData[9] = digitalRead(DB6);
  rawData[10] = digitalRead(DB5);
  rawData[11] = digitalRead(DB4);
  rawData[12] = digitalRead(DB3);
  rawData[13] = digitalRead(DB2);
  rawData[14] = digitalRead(DB1);
  rawData[15] = digitalRead(DB0);
  //convert into 16bit 2s compliment and store in a variable array
  adcData[thisChannel] = rawData[0] | (rawData[1] << 1) | (rawData[2] << 2) | (rawData[3] << 3) | (rawData[4] << 4) | (rawData[5] << 5) | (rawData[6] << 6) | (rawData[7] << 7) |  (rawData[8] << 8) | (rawData[9] << 9) | (rawData[10] << 10) | (rawData[11] << 11) | (rawData[12] << 12) | (rawData[13] << 13) | (rawData[14] << 14) | (rawData[15] << 15);
  //send ADC pin high to say we have read the first channel
  digitalWrite(RD, HIGH);
  //repeat for n channels
  }
}

//counting pulses ISRs
void pulseCounter1(){
  // Increment the pulse counter
  pulseCount1++;
}
void pulseCounter2(){
  // Increment the pulse counter
  pulseCount2++;
}
void pulseCounter3(){
  // Increment the pulse counter
  pulseCount3++;
}

I think the shield doesn't use 53 as CS. usually pin 10 or 4 is used for Uno compatible shields. but pin 53 must be used as OUTPUT if Mega is SPI master

The SD card uses SPI for communications.  You appear to be using those pins for some other purpose.  If you want to use the SD card, then you need to choose other pins and let the SD card have 50, 51, 52, and 53.

Thank you Delta G, you are a G!  I was using an old version of my sketch, what an idiot! I had all the wires connected to the correct pins but hadn't double checked it in the sketch - schoolboy error 101. Thanks again and like I said, I'm eternally grateful. Hit me up if you're ever in Blighty - I owe you a drink at the very least.  Cheers,  Michael


text:
SN74HC595 Shift Register Issue
I'm trying to use the popular SN74HC595 Shift Register, but I think something isn't right because when the bits are submitted to the register it comes out with something similar but not the same.
#define Latch 9
#define CLK 10
#define DATA 8

byte led = B10110111;

void setup()
{
  pinMode(Latch, OUTPUT);
  pinMode(CLK, OUTPUT);
  pinMode(DATA, OUTPUT);

  digitalWrite(Latch, LOW);
  shiftOut(DATA, CLK, MSBFIRST, led);
  digitalWrite(Latch, HIGH);
}

void loop()
{
  //LOOP
}

After this completes I receive an output of 10110101 instead of 10110111. Has anybody had the same area? Any fixes? Could my chip be faulty inside?
Schematic:

is a specific bit failing?

I guess you have just forgotten to draw the gnd and 5V lines to the breadboard?

Lack of decoupling capacitors?

@jsotola It can be any bit that fails but usually within the last 3

@Wirewrap Yes I forgot to draw the GND, and 5V to the breadboard, but they are connected

I so not know if this helps, but I had a similar "random data" problem with my shift register. It turned out that there wasn't a tight connection between one of the data in/enable pins and VCC. So I made sure all my jumpers were firm in the breadboard (bent the pins just a tiny bit) and tried another breadboard.

I'm with Magenko, you need  a 0.1uF cap from the shift register's Vcc pin to the nearest Gnd.  I've strung up 9, 18, 27, 36, 45 shift registers and clocked in data a 8 MHz use SPI and not had issues. Check your connections and add a cap.  Make sure the clear pin is pulled high and the output enable pin is pullled low.


text:
ESP12E Boot vs SPI
I was wondering how I could overcome the next issue;
My ESP8266 12E is connected as follows:

GPIO0 ground if needed to program, vcc otherwise
GPIO2 vcc
GPIO15 ground

Bootmodes explained in the this schematic
I also want to connect a MCP3002 to my ESP. However to use SPI I also need the GPIO15 pin to be connected to the Chip Select pin.
MCP connections explained in this article

I tried connecting the GPIO15 pin from the ESP to the CS pin of MCP3002 and connecting ground in between. This did not work though, should I switch/remove the ground after boot somehow?
(Or should I connect it differently?)

The io 15 is SS if esp8266 is slave. If esp8266 is SPI master, you can choose any free pin as CS of the slave.

The esp8266 arduino boards package SPISlave library examples have a solution for master if esp8266 is slave.
The state of the boot pins is required only at boot. You should wire boot pins over a 10 kOhm resistor to create a pull-up/pull-down which can be override by pin output state to use the pins for devices which are OK with or need pull-up or pull-down, for example momentary switches (buttons).

I suppose my ESP8266 is the Master and my MCP3002 is the Slave? This means I can connect the MCP3002 CS to any other available pin of the ESP8266?

Thank you, I will try it tonight and will give feedback what it does!

the libraries you use are old and I don't see how to change the CS pin. I would try to use some other Arduino MCP3002 library with the standard SPI library of esp8266 boards package

I have no idea what you are talking about. This question is about wired connections and has nothing to do with libraries. The links are only a reference for wires, not for libraries what so ever,..

the article in second link has link to libraries

Thanks! It works like a charm =). Can you also give some more info / background on why I can use any pin and not just the CS pin?

SPI is a bus. on master you need so many pins CS pins as many devices you attach to it. this CS pins are not handled by the MCU's SPI peripheral, but by the library. if SPI peripheral of the MCU is in slave mode it must use the dedicated pin. it is true for ATmega MCUs and for esp8266. but some other MCU can map different pins to peripherals. and as other exception  the SPI peripheral on the esp8266 has a strange mode of overlapping SPI which can use only dedicated CS pins in master mode to share with other devices the SPI interface dedicated to flash memory.


text:
Wire SlaveReceiver : will the registered function in onRecieve interrupt/conflict with loop block?
I am currently researching on I2C, and I made a configuration that has MasterWriter that transmits data to a SlaveReceiver that will store the data received from Master, into an SD card, and then transmit the same line of data by GPRS onto my back end.
Now the new requirement needs some kind of a caching system, so that if the GPRS failed to transmit, it'll instead save into the SD card under a different filename (the previous step of saving into SD Card is still done but it's for another purpose), so when the GSM signal needed has recovered it'll read the cached/backed-up data, and then transmit the backed-up data. So that means I'll use the loop block (which currently only has one line of delay function).
My question is, will the triggered function "receiveEvent" registered in setup for Wire Slave :

Wire.onReceive(receiveEvent);

conflict with the ongoing loop block where the system reads the backed-up data and sends the backed-up data?
Here's my SlaveReceiver code :

#define ONLINE_MODE 1 //  turn on for GSM.
#define CACHE_MODE 1 //   turn on for SD-based caching
#define I2C_MODE 1  //    turn on for I2C mode SDA-SCL

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

#if ONLINE_MODE
// Sim900
#include "GSM.h"
SIM900 gprs;
#endif

#if I2C_MODE
#include <Wire.h>
#endif

#if CACHE_MODE
//SD Card
#include <SPI.h>
#include <SD.h>
#define DEBUG_SD 1
#define SD_CS_PIN 4
File cacheFile;
#endif

void setup()
{
    console.begin(9600);
    while (!console);

    #if CACHE_MODE
     //SD Card
    Serial.print(F("Initializing SD card..."));

    if (!SD.begin(SD_CS_PIN)) {
      Serial.println(F("initialization failed!"));
      while (1);
    }
    // open the file. note that only one file can be open at a time,
    // so you have to close this one before opening another.
    cacheFile = SD.open("CACHE.txt", FILE_WRITE);
    Serial.println(F("SD Card initialization done."));
    #endif

    #if ONLINE_MODE
    gprsSetup();
    #endif

    #if I2C_MODE
    Wire.begin(8);                // join i2c bus with address #8
    Wire.onReceive(receiveEvent); // register event
    #endif
    console.println(F("SLAVE GSM SD READY"));

}

// function that executes whenever data is received from master
// this function is registered as an event, see setup()
// [Q] : will this interrupt/conflict with loop() if loop is still ongoing?
void receiveEvent(int howMany) {
  #if DEBUG_I2C
  Serial.print(F("available bytes : "));
  Serial.print(howMany);
  Serial.print(F(" or "));
  Serial.println(Wire.available());
  #endif

  #if I2C_MODE
  char jsonData[128]="";
  while (Wire.available()) { // loop through all but the last
    char c = Wire.read(); // receive byte as a character

    int len = strlen(jsonData);
    jsonData[len] = c;
    jsonData[len+1] = '\0';

    #if DEBUG_I2C
    Serial.print(c);         // print the character
    #endif

    if (c == '}'){

      #if CACHE_MODE
      writeToSd(jsonData);
      #endif

      #if ONLINE_MODE
      gprsSequence(jsonData);
      #endif

      #if DEBUG_I2C
      Serial.println(F("SAVING TRIGGERED"));
      Serial.println(jsonData);
      #endif
    }

  }
  #endif
}

void writeToSd(char *jsonToWrite){

  #if CACHE_MODE
  // open the file. note that only one file can be open at a time,
 // so you have to close this one before opening another.
  cacheFile = SD.open("CACHE.txt", FILE_WRITE);
  if (cacheFile) {
    cacheFile.write(jsonToWrite);
    cacheFile.close();
  }

  #if DEBUG_SD
  Serial.println(F(" << "));
  // re-open the file for reading:
    cacheFile = SD.open("CACHE.txt");
    if (cacheFile) {
    Serial.println("CACHE.txt:");

    // read from the file until there's nothing else in it:
    while (cacheFile.available()) {
      Serial.write(cacheFile.read());
    }
      // close the file:
      cacheFile.close();
    } else {
      // if the file didn't open, print an error:
      Serial.println(F("error opening CACHE.txt"));
    }
  #endif
  #endif

}

void loop() {
    // i wanted to code the cached-data sending here
    delay(2000);
}

void gprsSetup() {
  //... cleared for brevity
}

void gprsSequence(char *jsonData) {
    //... cleared for brevity. the point is, this function is to send the jsonData by GPRS
}

Generally the onReceive callback function is called from an ISR in the Wire library. That means, that no other interrupts can be handled during that time. For this reason an ISR always should be as short as possible. Writing to the SD card is a rather long process and it also uses interrupts, so it might block forever, when used in an ISR (though I'm not sure, since I didn't look through the SD library). You should do the SD card stuff outside of the ISR. In the ISR you can receive the I2C message and then set a flag variable, that will tell the code in the loop() function, that new data is available and that it can start processing it. That way your ISR stays short and the other operations will not be blocked by it. Do the same with the direct sending of GPRS data.
Also note, that transmitting Serial data inside of an ISR also does not work for the same reason (Serial relies on interrupts). The calls to Serial.print() or Serial.write() will only fill the libraries internal buffer. The data will get transmitted after the ISR was left. If you try to print/write data to Serial, when the buffer is full, the library will block, until the buffer has again space for sending the data, which will never happen inside the ISR. So you should be cautious with writing Serial inside an ISR. A bit doesn't hurt, but it can get a big problem.

will the triggered function "receiveEvent" registered in setup for
  Wire Slave Wire.onReceive(receiveEvent); conflict with the ongoing
  loop block where the system reads the backed-up data and sends the
  backed-up data?

From the general logic there cannot happen more than 1 specific data operation on the SD card at the same time. If you are currently writing one file, you cannot simply break the transmission through an interrupt and writing another file without breaking things. The transaction has to be completed, or you will fastly corrupt your file system. But, as I wrote above, this isn't really possible either way, because the SD card calls will not work properly inside of an ISR. So just put all the GPRS and SD card code into the loop() function and trigger the corresponding code blocks with a flag from the ISR. That way nothing can conflict here.


text:
Slow serial communication with arduino and response on the application?
Currently, I'm doing a project as I want to use my Arduino Mega 2560 as an interface to my computer with a photo interrupter and stepper motor. So I need to send some commands and data to the Arduino from my PC. However, after upload the code to the board, I found out the serial communication of the Arduino quite slow. In fact, the moment after the code done uploading, my command in the Serial Monitor takes almost a second to execute. Below is the details about the code:-
    // Include the Arduino Stepper Library
#include <Stepper.h>

// Number of steps per output rotation
const int stepsPerRevolution = 200;

// Create Instance of Stepper library
Stepper myStepper(stepsPerRevolution, 12, 11, 10, 9);

int val;
int counter = 0;

void setup()
{
  // set the speed at 200rpm:

  myStepper.setSpeed(200);
  // initialize the serial port:
  Serial.begin(9600);
}

void loop()
{
  val = analogRead(A0);
  Serial.println(val);

  myStepper.step(stepsPerRevolution);
  counter = counter + 1;
  Serial.println(counter);

if (val > 200){
    Serial.println("it is running");

   } else {
    myStepper.setSpeed(0);
    Serial.println(counter);

   }

}

Any help so much appreciated.

so why not set a higher baud rate?

About a second between opening the serial monitor and the first response arriving? Yes. That's normal. That's called the bootloader executing. If you want faster then use a board that doesn't use a serial bootloader, or delete the bootloader and program the board with a hardware programmer.


text:
Connect 20 12v led to an arduino mega
I want to control about 20 leds with an arduino mega.
This leds works with 12v voltage.
I tried to put 20 relays but this solution is not good for me because leds will often blink
I have also tried transistors but it needs to make a pcb.
I am looking for a solution without having to create a pcb
Any idea ?
Thanks

something like this perhaps?  https://i1.wp.com/media.boingboing.net/wp-content/uploads/2017/07/IMG_3397.jpg?fit=680%2C429&ssl=1

You need to be able to turn these LEDs on and off individually? If you only need to turn them all on or off as a group you could use a single transistor.

If you're using relays correctly then your LEDs should not blink. There are "digital" relay modules that are made to be driven from 5V CMOS logic, but 20 relays will take a lot of power. Transistors are a much better bet.

You can use the commonly available L298N module to drive four of your LEDs with each module. That means you would need five of them.

Those modules are suitable for driving either one stepper motor, two DC motors (in both directions), or four "unidirectional" loads such as your LEDs.
The input can be connected directly to your MEGA, but you may need additional series resistors depending on the LED you use (though this likely does not apply for LEDs specified as "12V").
There are also LED driver eval boards available which may suit your needs:
https://www.digikey.de/product-detail/de/adafruit-industries-llc/1455/1528-1019-ND/4990768

The ULN2803 is a chip with 8 darlington transistors in it designed for driving higher voltage, low-ish current, loads like this.  With 3 of them you have 24 channels to drive your LEDs.
You can get them on a breakout board quite easily, or as a DIP chip for working with breadboards.

This sounds like a good solution. A DIP package with 8 darlingtons on it should be able to handle 8 LEDs, and 3 DIP chips would fit on a pretty small breadboard or PCB. Transistors are better/easier to deal with than relays for modest current DC loads like this anyway.

Three TPIC6B595 shift registers, controlled by 3 pins from the Mega, can do this easily. Shift in 3 bytes with on/off state of the LEDs.
Can sink 150mA per output from 12V source.  The LEDs need current control, from simple resistor for 20mA loads, to a constant current driver per LED for higher current LEDs.
I used them to sink current from 12V for the LED strings in this display. The small digits needed ~ 20mA per segment, the larger digit is really 2 groups of 3 LEDs, drawing about 40mA per segment. One shift register per digit.
https://www.youtube.com/watch?v=6HZ0Mr51jUY

Try s MOS- FET transistor.  Its not expensive and easy to drive.  Can be directly connected to the Arduino.  Look for standard circuit diagrams.  1 P- Mos Fet and 1 Resistor per channel,  esch can drive several Amperes st 12V...

You don't need gate resistors for logic-level MOSFETs. They have capacitive inputs just like CMOS logic chips, and draw almost no input current.

Connecting up 20 single transistors would be really tedious, vs 3 chips.  I even made a board with a 328P, FTDI module, and 3 shift registers to drive 24 LEDs for  an hours/5 minute intervals clock display.  Very compact, about <25x50mm if I recall. Board with 4 shift registers to coontrol gates of 32 MOSFETs to drive larger loads with screw terminal connectors was much bigger, 100mm x100mm. And no microcontroller.


text:
Choosing between ESP32 and Arduino Pro Mini
This is probably a fundamental question but I am hoping to get some pointers on how to chose between Arduino Pro Mini and ESP 32.
I am hoping to make a wrist based wearable like fitbit. Three primary needs are

Accelerometer or MPU module is important to collect movement data.
Wi-fi is not important because I think bluetooth would be enough to sync the data to a cell phone.
Battery management is of course more critical as I want it to last longer.
Smaller the dimensions, better for design and aesthetics.

My first choice was using Arduino  pro mini because it is smaller and less  power consuming.  However, we do need to manually connect BLE module like HC-05 to it. Now I think ESP32 could also be a good option because it has both wifi and bluetooth although I do not care about wifi.
Now I found these useful comparisons on web

Arduino and NodeMcu (ESP8266) like this
Between ESP32 vs ESP8266 like this
Between Nano or pro mini like this

However, none of them help me directly in my case. I understand ESP32 and ProMini are meant for different things and hence should not be compared for a single project. May be I am missing something more fundamental. Any guidelines in this would really help.

why not compare with nRF5? 32bit ARM Cortex M0 with Bluetooth

Absolutely. I was about to suggest the same thing. Something like the nRF51822 would be a far better fit for your project.


text:
read with Arduino SSI encoder signal
I'm stuck in my project, I try to read an absolute encoders angular position with my Arduino.
I used and cabled a differential line receiver and driver between Arduino and the encoder, like explained in the 2 following links:

Figure 2.1 here
Input circuitry of subsequent electronics

Here are the specifications of the encoder that I try to read.
Here is my Arduino code :
const int CLOCK_PIN = 5;
const int DATA_PIN = 6;
const int BIT_COUNT = 25;

void setup() {
  //setup our pins
  pinMode(DATA_PIN, INPUT);
  pinMode(CLOCK_PIN, OUTPUT);

  //give some default values
  digitalWrite(CLOCK_PIN, HIGH);

  Serial.begin(115200);
}

void loop() {
  float reading = readPosition();

  if (reading >= -0.5) {
      //Serial.print("Reading: ");
      //Serial.println(reading,2);
  }

  delay(200);
}

//read the current angular position
float readPosition() {
  unsigned long sample1 = shiftIn(DATA_PIN, CLOCK_PIN, BIT_COUNT);
  unsigned long sample2 = graytobin(sample1, BIT_COUNT);
  delayMicroseconds(25);  // Clock mus be high for 20 microseconds before a new sample can be taken

  Serial.print("grey: ");
  Serial.println(sample1, BIN);
  Serial.print("binary: ");
  Serial.println(sample2, BIN);
  Serial.print("decimal: ");
  Serial.println(sample2 & 0x0FFF);
  Serial.print("\n");

  return ((sample2 & 0x0FFF) * 360UL) / 4096.0;
}

// gray to binary
int graytobin(int grayVal, int nbits ) {
  int binVal = 0;
  bitWrite(binVal, nbits - 1, bitRead(grayVal, nbits - 1)); // MSB stays the same
  for (int b = nbits - 1; b > 0; b-- ) {
    // XOR bits
    if (bitRead(binVal, b) == bitRead(grayVal, b - 1)) { // binary bit and gray bit-1 the same
      bitWrite(binVal, b - 1, 0);
    }
    else {
      bitWrite(binVal, b - 1, 1);
    }
  }
  return binVal;
}

//read in a byte of data from the digital input of the board.
unsigned long shiftIn(const int data_pin, const int clock_pin, const int bit_count) {
  unsigned long data = 0;

  for (int i=0; i<BIT_COUNT; i++) {
    data <<= 1;
    digitalWrite(clock_pin,LOW);
    delayMicroseconds(1);
    digitalWrite(clock_pin,HIGH);
    delayMicroseconds(1);

    data |= digitalRead(data_pin);

  }

  return data;
}

I'm still able to receive information with my Arduino from the encoder but they are totally random. Here is an example of the output I get (I didn't move the encoder during this exercition):
grey: 1001111101110100011111001
binary: 11111111111111111011000010101110
decimal: 174

grey: 111110110010001111100111
binary: 11110101000101
decimal: 3397

grey: 0
binary: 0
decimal: 0

grey: 0
binary: 0
decimal: 0

grey: 0
binary: 0
decimal: 0

grey: 0
binary: 0
decimal: 0

grey: 1111111111111111111111111
binary: 11111111111111111010101010101010
decimal: 2730

grey: 1011001110011011100010001
binary: 10010111100001
decimal: 1505

grey: 1100111011011100100011111
binary: 11111111111111111101000111101010
decimal: 490

grey: 1101110110111001000111111
binary: 101110000101010
decimal: 3114

grey: 0
binary: 0
decimal: 0

grey: 0
binary: 0
decimal: 0

grey: 0
binary: 0
decimal: 0

grey: 0
binary: 0
decimal: 0

grey: 111111
binary: 101010
decimal: 42

grey: 111011011100100011100111
binary: 11111111111111111000111101000101
decimal: 3909

grey: 1100111001101110010001111
binary: 11111111111111111001011100001010
decimal: 1802

grey: 1100111011011100100011111
binary: 11111111111111111101000111101010
decimal: 490

grey: 0
binary: 0
decimal: 0

grey: 0
binary: 0
decimal: 0

grey: 0
binary: 0
decimal: 0

grey: 0
binary: 0
decimal: 0

I don't know how to diagnose the problem, and how to find it.

Please add wiring of circuit. Double check that ground and cables. Also try a lower clock frequency, e.g. delayMicroseconds(2).


text:
How to Run Stepper motor through Serial Communication
I am trying to run a Stepper motor from my c++ application, from which I sent commands but its not running not sure why would it not run, outside serial check it run but inside serial check it not run.
Here is my code, not sure what am doing wrong, my first time with Arduino.

#include <AccelStepper.h>

#define BAUD 9600

// CNC Shield V3  Step and Dir pins on Mega 2560
#define step_pin_x 2
#define dir_pin_x 5
#define MOTOR_X_ENABLE_PIN 8
// Drive A4988
#define motorInterfaceType 1

AccelStepper stepper_X = AccelStepper(motorInterfaceType, step_pin_x, dir_pin_x);

void setup() {
  Serial.begin(BAUD);
  pinMode(53, OUTPUT);   // for red led it pin # 53
  pinMode(MOTOR_X_ENABLE_PIN, OUTPUT);  // for X stepper motor

    stepper_X.setMaxSpeed(1000);
    stepper_X.setSpeed(500);
}

void loop() {
    String input;
  //If any input is detected in arduino
  if(Serial.available() > 0){
    //read the whole string until '\n' delimiter is read
    input = Serial.readStringUntil('\n');

    if (input.equals("ON")){
       digitalWrite(53, HIGH);   // Turn ON RED LED
       stepper_X.runSpeed();      // Suppose to run stepper motor .. but not working
       Serial.println("X Motors:: "+input);

    }else if (input.equals("OFF")){
       stepper_X.stop();
       digitalWrite(53, LOW);    // Turn OFF RED LED
       Serial.println("X Motors:: "+input);
    }

  }else{
  //  stepper_X.runSpeed();      // if uncommented stepper motor will run
  }
}

Update
so it seems its code blocking issues
i update my code according to tut : https://majenko.co.uk/blog/reading-serial-arduino
    char buf[80];

    int readline(int readch, char *buffer, int len) {
        static int pos = 0;
        int rpos;

        if (readch > 0) {
            switch (readch) {
                case '\r': // Ignore CR
                    break;
                case '\n': // Return on new-line
                    rpos = pos;
                    pos = 0;  // Reset position index ready for next time
                    return rpos;
                default:
                    if (pos < len-1) {
                        buffer[pos++] = readch;
                        buffer[pos] = 0;
                    }
            }
        }
        return 0;
    }

void loop() {
   if (readline(Serial.read(), buf, 80) > 0) {
   if(strcmp("n", buf) == 0){
          digitalWrite(53, HIGH);
         stepper_X.setMaxSpeed(1000);
         stepper_X.setSpeed(500);
          stepper_X.runSpeed();
          Serial.print("All Motors:: ");
          Serial.print(buf);

        }
    }
}

now its working ok
Update 2 : c++ sending command via Serial
    std::string input_command = "ON";
    //Creating a c string
     char *c_string = new char[input_command.size() + 1];
     //copying the std::string to c string
     std::copy(input_command.begin(), input_command.end(), c_string);
     //Adding the delimiter
     c_string[input_command.size()] = '\n';

// using this serial lib : https://github.com/manashmndl/SerialPort
   writeSerialPort(c_string, MAX_DATA_LENGTH);

Have you checked, if the data get's correctly transmitted by echoing it back and showing it in your application?

@chrisl ya data reached correctly even i get reply from Arduino like X Motors ON  , OFF etc

Are you sure you are sending "ON\n" rather than "ON\r" or "ON\r\n"?

@EdgarBonet  Yes am Sending "ON\n"  .... the red LED turn ON and OFF with ON/OFF command which mean that if (input.equals("ON"))  check become valid also i get reply that X motor :: ON

Per the documentation of the AccelStepper’s runSpeed()
method:

You must call this as frequently as possible, but at least once per
  step interval,

It appears the AccelStepper library is not compatible with blocking
code. Not a big deal, blocking code is almost always bad practice
anyway. However, Serial.readStringUntil() is a blocking function: it
will prevent the program from doing any useful work.
You have to read the serial port in a non-blocking fashion,
use the commands to set the motor speed, and always call runSpeed() as
frequently as possible.

Botne , thanks for valuable information , one another Question i have , i noticed serial communication is slow , i mean it take about 2 sec to arduino to get message and the motor start moving , so can you tell how to make it robust , i mean something like real time communication , as am working on SMT project so i will need to move stepper motors to their locations fast as soon as possible  but this is slow it take about 3 sec to get response and then motor move

@user889030: Slow communication is most commonly the sign of a Stream input method timing out. For example, readStringUntil() times out when it can't find the terminator character in the input stream (are you sure you send the '\n'?). The default timeout duration is one second. See here the list of timeout-based Stream methods. You shouldn't have this problem if you do send the terminator character, or if you parse the input stream as in Majenko's tutorial.

Botnet  ya ma sending '\n'  with it , you can see i added some c++ code  , thanks


text:
ESP - Nodemcu amica - attachInterrupt crash program
I get new boards from the shop but they are little different from the previous version. I got software what works ok on Nodemcu lolin v3 now I get Nodemcu Amica what is almost same board but if I got attachInterrupt function in the program it crashes immediately.
    attachInterrupt(6, bowlingCall, RISING);
//attachInterrupt(digitalPinToInterrupt(D1), statekCall, RISING);

I try different pins but not change. I debug all program(comment all out and left just attachInterrupt and it crashes again).
    ets Jan  8 2013,rst cause:2, boot mode:(3,6)

load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v8b899c12
~ld

The board cycle in the reboot sequence, even serial output do not work ok. Why did esp crash at attachInterupt on this board?

https://github.com/esp8266/Arduino/issues/6142

thanks @Juraj.
Ok, so all you need is rewrite all your interrupt function.
For example:
void getStatusFromMaster()

to
void ICACHE_RAM_ATTR getStatusFromMaster()


text:
Arduino Mega reading same information that it's sending out via serial
So I have an Arduino Mega and I'm attempting serial communication with another device, and I ran into this weird issue.
Let's say I use Serial1.write to send out hex A-F. If I read on that same port (Serial1, print out what I read on Serial0), with NO wires plugged in the serial port, I get a mirror of what I'm sending out in my read function. I've tested this theory on multiple serial ports, as well as different Megas.
How is this interference happening? Do I have an incorrect understanding of the serial buffers? What can I do to stop it? It's causing interference in communicating with my external device.
Here is a super short program to test this theory.
void setup()
{
  Serial.begin(9600);
  Serial1.begin(115200);
}

void loop()
{
  char test[15];
  for (int i = 0; i < 15; i++)
    test[i] = i;

  for (int i = 0; i < 15; i++)
     Serial1.write(test[i]);

  while(Serial1.available() > 0 )
   {
    byte c = Serial1.read();
    Serial.print(' ');
    Serial.print(c, HEX);
  }
}

UPDATE:  I came back the next day with my O-scope and the yellow line is the TX and the blue line is the RX. I was not getting the crosstalk anymore in the Serial port, but on the scope shows the RX line was only being effected about 250mV in perfect unison to the TX. I tried connecting everything back up the same way but I was not able to replicate the issue. Somehow whatever I had going on when I posted this was causing the RX line to be affected great enough for the Mega to pick up on it over serial. For now I'm just blaming it on escaped aliens from Area 51 :)

it is acting as if the local echo is enabled ... there does not appear to be a setting for it though

does this happen if you swap serial and serial1? What happens if you try them both at 9600?

you reinvented radio communication :-)

@esoterik idk, I need serial for seeing my data so I didn't swap. I tried it on Serial2, same issue, then I tried it on Serial3 and it worked better, but not great. I tried different baud rates as well

Note that a scope typically has 1 MΩ input impedance. This would be increased by a factor 10 if using a 10× probe. Connecting the scope to RX is equivalent to adding an extremely weak pull-down resistor, which is enough to significantly reduce the cross-talk effect.

I got the same results from my setup; 0-5V on the Tx line, 0-.3V on the Rx line.  As an experiment I connected two parallel 30cm wires to Tx & Rx. This resulted in a higher cross-talk level, but still did not result in any 'echo reads'. I'm pretty sure that in order to get the necessary 0-3V or so on the Rx line to actually get successful data reads would require some sort of wired connection.  I think your escaped aliens may have pulled one over on you ;-).

I ran a slightly modified version of your test code on a Mega 2560 and got no echo at all;  Unless I totally misunderstood your problem description, there must be something else going on.  Here's the code I ran:

char test[15];

void setup()
{
    Serial.begin(9600);
    Serial1.begin(115200);
    for (int i = 0; i < 15; i++)
    {
        //Serial.print(i);
        test[i] = i;
        Serial.print(test[i],HEX);
    }
    Serial.println();

    for (size_t j = 0; j < 15; j++)
    {
        Serial.print("test["); Serial.print(j);
        Serial.print("] = ");Serial.println(test[j],HEX);
    }
}

void loop()
{
    for (int i = 0; i < 15; i++)
    {
        Serial1.write(test[i]);
    }

    Serial.println(Serial1.available());

    while (Serial1.available() > 0)
    {
        byte c = Serial1.read();
        Serial.print(' ');
        Serial.print(c, HEX);
    }
}

And here's a bit of the output seen on Serial0:
Opening port
Port open
VMDPV_1|1_�Se�
0123456789ABCDE
test[0] = 0
test[1] = 1
test[2] = 2
test[3] = 3
test[4] = 4
test[5] = 5
test[6] = 6
test[7] = 7
test[8] = 8
test[9] = 9
test[10] = A
test[11] = B
test[12] = C
test[13] = D
test[14] = E
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0

As you can see, the Serial1 read buffer was always empty.
Did I misunderstand something you said?

I updated my post, see the new info. I ran the same thing again a few days later and I couldn't replicate it, however the perfectly matching RX and TX on the scope leads me to believe that something I had going on made the interference great enough that I could read it back.

Thank you for helping out


text:
ESP8266 Huzzah error: "Failed to connect to ESP8266: Timed out waiting for packet header"
I am trying to follow this tutorial but when I get to the step...
"Once the ESP board is in bootload mode, upload the sketch via the IDE"
..I get the following error in Arduino IDE:
File "[path]/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.5.2/tools/esptool\esptool.py", line 468, in connect
    raise FatalError('Failed to connect to %s: %s' % (self.CHIP_NAME, last_error))
esptool.FatalError: Failed to connect to ESP8266: Timed out waiting for packet header

Any ideas about how to fix this?

it is not in bootload mode


text:
Making a PID Controller for BAR 30 pressure sensor
I am having issues with my PID controller  for a BAR 30 depth sensor. The issue that I have is my ESC have two initial start up { 1500 - 1900} is min - max respectively clockwise and { 1500-1900} is max respectively counter clockwise.
What I want is for me to set a depth and I can submerge to a certain depth and lock in at that certain depth.
#include <PID_v1.h>
#include <MS5837.h>
#include <Wire.h>
#include <Servo.h>
MS5837 sensor;
Servo vertical_thruster1;

// Variables

float current_depth ;
float set_depth = 0.50 ; //  depth u wish to go in meters
float PID_error = 0;
float previous_error = 0;
float elapsedTime,  Time , timePrev;
double pwmvertical_thruster1 = 1440;

int s;

float PID_value = 0;
float PID_p = 0;
float PID_d = 0;
float PID_i = 0;
//PID constants
float kp = 100;
float ki = 0.003;
float kd = 5.2;

void setup() {
  Serial.begin(9600);
 vertical_thruster1.attach(4);
   vertical_thruster1.writeMicroseconds(1500);

 Time = millis ();

 ///Bar 30 Configuration

  Serial.println("Starting");
  Wire.begin();
 while (!sensor.init()) {
Serial.println("Init failed!");
Serial.println("Are SDA/SCL connected correctly?");
Serial.println("Blue Robotics Bar30: White=SDA, Green=SCL");
Serial.println("\n\n\n");
delay(2000);
  }
  sensor.setModel(MS5837::MS5837_30BA);
  sensor.setFluidDensity(997); // kg/m^3 (freshwater, 1029 for seawater)
}

void loop() {

///*
// First read the current value of the depth sensor
sensor.read();
current_depth = sensor.depth();

timePrev = Time;
Time= millis();
elapsedTime = ( Time - timePrev) / 1000;

// calculate the error between the set depth and current depth
 PID_error =  set_depth - current_depth ;

 // Calculate the P Value
 PID_p = kp * PID_error;
   Serial.print("PID_p: ");
    Serial.print(PID_p);
    Serial. println ( "\t\t");
// Calculate the i value in a range on +-0.3

 if (-0.2 < PID_error < 0.2)
 {
  PID_i = PID_i + (ki * PID_error);
 }
Serial.print("PID_i: ");
Serial.print(PID_i);
Serial. println ( "\t\t");
// Calculate the d value
 PID_d = kd*((PID_error - previous_error)/elapsedTime);
Serial.print("PID_d: ");
Serial.print(PID_d);
Serial. println ( "\t\t");
// The total PID value
PID_value = (PID_p + PID_i + PID_d) ;

// range for the blue robotics esc

if ( PID_value < -150)
 {
 PID_value = -150;
  }
  if( PID_value >150)
  {
  PID_value = 150;

  }
  Serial.print("PID_value: ");
  Serial.print(PID_value);
  Serial. println ( "\t\t");
 // calcualte the pwm

 s =  (pwmvertical_thruster1 + PID_value  );
 if(s < 1350)
{
 s= 1450;

}
else if(s> 1650)
{
  s=1550;

}
  Serial.print("Depth: ");
  Serial.print(sensor.depth());
  Serial.println(" m");
  Serial.print ( "Speed s  ");
  vertical_thruster1.writeMicroseconds(s);
  Serial.print( s) ;
  Serial. println ( "\t\t");
  previous_error = PID_error;
  //  */
  delay(300);
 }

A PID controller should be a good match for your application, but it appears that your code doesn't take advantage of the PID_v1 library at all; a PID_v1 object is never declared, and it appears you are attempting to manually compute what the PID library is designed to do for you automatically.
I would recommend you 'start slow and simple' by learning how to use a PID controller in its most basic form.  The PID library has a very basic example, which I have modified slightly to demonstrate how a PID controller works.  I tested this example with a UNO, a potentiometer (variable resistor) and a capacitor. The resistor and capacitor values aren't critical - I used the first things I found in my parts box.  The output on Pin 3 is a PWM pulse train signal, and the resistor/capacitor combination filters this pulse train to a variable level analog signal, which the PID controller sees as the analog 'Input' on A5.
Once you have this running, you can vary the pot value to see how the PID changes the output value in order to achieve the setpoint value on the input, and you can vary the setpoint and PID parameters to play around with different configurations.  Once you are comfortable with basic PID operation, you should then be able to configure it properly for your application.
Hope this helps,
#include <PID.h>

 //Define Variables we'll be connecting to
double Setpoint, Input, Output;

//Specify the links and initial tuning parameters
PID myPID(&Input, &Output, &Setpoint, 2, 5, 1, DIRECT);

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

    //initialize the variables we're linked to
    //Input = analogRead(0);
    Input = analogRead(A5);  //I used A5 as A0 was unavailable
    Setpoint = 100;

    //turn the PID on
    myPID.SetMode(AUTOMATIC);
}

void loop()
{
    //Input = analogRead(0);
    Input = analogRead(A5); //I used A5 as A0 was unavailable
    myPID.Compute();
    analogWrite(3, Output);
    Serial.print("Input = "); Serial.print(Input); Serial.print(", Output = "); Serial.println(Output);
    delay(100);

}


text:
HardwareSerial Indexing Array
How should I index HardwareSerial ports into a single array?.
This compiles, but do not work.
HardwareSerial Serials[]={Serial,Serial1,Serial2,Serial3};

void setup(){
    for (int i=0;i<=3;i++){
        Serials[i].begin(38400);
        while (!Serials[i]);
    }
}

char s;
void loop(){
    for (int i=0;i<=3;i++){
        if (Serials[i].available()){
            s=Serials[i].read();
            Serials[i].write(s);
        }
    }
}

please, next time provide code that compiles

your code makes copies of Serials into items in the array of HardwareSerials. To use the original Serial objects, store and use pointers.
HardwareSerial* Serials[]={&Serial,&Serial1,&Serial2,&Serial3};

void setup(){
    for (int i=0;i<=3;i++){
        Serials[i]->begin(38400);
        while (!*Serials[i]);
    }
}

void loop(){
    for (int i=0;i<=3;i++){
        if (Serials[i]->available()){
            char s=Serials[i]->read();
            Serials[i]->write(s);
        }
    }
}


text:
Code that worked in Uno is not working in Mega 2560
I send data with Android and read it from the Arduino serial screen. When I use UNO, I can read the data smoothly. When I use MEGA, it uploads the code without error, but does not transfer data on the serial screen. Can you tell me why?
#include <SoftwareSerial.h>

SoftwareSerial bluetooth(2,3);    // TX,RX
int bar_analog=0;
int head_analog=0;
int bar_anim=0;
int strip_anim=0;
int motor_speed=1;
int direct=0;
int level=0;
boolean debug = true;

void setup() {
  Serial.begin(9600);
  bluetooth.begin(9600);
  Serial.println("Program is starting...");
  Serial.println("by Berke Ogulcan Parlak");
}

void loop() {
  if (bluetooth.available()) {
    while (bluetooth.available())
    {
      bar_analog = bluetooth.parseInt();
      head_analog = bluetooth.parseInt();
      bar_anim = bluetooth.parseInt();
      strip_anim = bluetooth.parseInt();
      motor_speed = bluetooth.parseInt();
      direct = bluetooth.parseInt();
      level = bluetooth.parseInt();
      if (debug) {
        Serial.print("Bar Brightness: ");
        Serial.println(bar_analog);
        Serial.print("Bar Animation Type: ");
        Serial.println(bar_anim);
        Serial.print("Headlight Brightness: ");
        Serial.println(head_analog);
        Serial.print("Strip Animation Type: ");
        Serial.println(strip_anim);
        Serial.print("Motor Speed Level: ");
        Serial.println(motor_speed);
        Serial.print("Direction: ");
        Serial.println(direct);
        Serial.print("Mast Goes: ");
        Serial.println(level);
        Serial.println("--------------------------------");
      }
      if (bluetooth.read() == '\n') {
        azdırma işlemleri bu satırda yapılacak..

      }
    }
  }

}

SoftwareSerial relies on the Pin Change interrupt. Not all pins on the Mega have pin change interrupts.
But that is all a moot point really, because when you're using a microcontroller that has lots of real hardware UARTs there is no call to be using SoftwareSerial in any case.


text:
i2c Connection for MCP4725(Dac) with Esp8266 wemos d1 mini
------------ This question has been edited ------------
note: Dac and Adc is12bits
my problem : I use two ESP. Using esp1, I read the Adc amount of the alternating signal (ECG) and send it to esp2 with UDP and I get it. Now, using the same amount of Adc, I would use the MCP4725 to convert the digital value of the Adc to the analog. But I don't know how to do it !

Do you need sine lookup table like default library example again ??!
If so, how is it done?!
I wrote the following code right now, what is your opinion?
Explain to me if my code is in error.

I just want the DAC output, to be the ADC signal input.
Code:
void loop () {

  int noBytes = Udp.parsePacket();
  String received_command = "";

  if ( noBytes ) {
    Udp.read(packetBuffer,noBytes);

    for (int i=1;i<=noBytes;i++)
    {
      received_command += char(packetBuffer[i - 1]);
    }
    int dac_value ;
    dac_value = received_command.toInt();
    Serial.print("dac value: ");Serial.println(dac_value);
    aPin = dac_value ;
    if (!si.i2c_start((I2C_7BITADDR<<1)|I2C_WRITE)) {
      Serial.println("I2C device busy");
      return;
    }

    else{
      Serial.println("i2c is worked");
    }

    for (byte i=1; i<noBytes; i++){
      si.i2c_write(aPin);
      si.i2c_rep_start((I2C_7BITADDR<<1)|I2C_READ);
      si.i2c_stop();
      delay(50);
    }
  }
}

I use #include <SlowSoftI2CMaster.h>.
si is: SlowSoftI2CMaster si = SlowSoftI2CMaster(4, 5, true);
Photo:

If the problem is how to interface the MCP4725, I recently answered a question about it, where is explained how to interface it correctly. Please read this. Also have a look at the Wire library and the MCP4725's datasheet

I'm waiting for answer..

Ok, I will explain the basic principles and give some tips. This won't be about your code, since it is neither compilable, nor does it make much of a sense to me.

The I2C Protocol: An I2C connection always needs 2 lines, SDA (which carries the data) and SCL (where the master outputs the clock signal). The communication always get's started by the master with a START CONDITION. Then it transmits the first byte, which consists of the 7 bits long address of the slave device and one bit, that shows if a read or a write operation will be performed. The slave - if there is any with that address - will then respond with an Acknowledgement. The master will transmit it's data and end the transmission with a STOP CONDITION or start a new transmission with a repeated start condition.
Choose the I2C library: You are using the SlowSoftI2CMaster library because it is architecture independent. As you are a beginner, you should use the SlowSoftWire library, which is a Wire-like wrapper library. It gives you the same interface, as the Wire library. That is good for beginners, since this hides some of the complexity and most examples and tutorials use the Wire library (so you can often copy the code structure). You have to install both libraries (SlowSoftI2CMaster and  SlowSoftWire) in your libraries folder, but you only need to include the SlowSoftWire library. Please look at the examples, that come with that library. I will refer to that library in the following points.
Using the SlowSoftWire library: You can declare and initialize the library as in it's simpleSlowWire.ino example. For transmitting a new value to the DAC, you have to first use beginTransmission() to configure the library for a master write transaction. Then place the data bytes in the libraries buffer with write(). And finally do the transmission with endTransmission() (this is the only place during this process, where the real I2C action happens on the bus). When you begin the transmission with beginTransmission() you must provide the correct address of the DAC. This is meant without the direction bit. The address of the MCP4725 consists of the device code 1100, the hardwired address pins A1 and A2, and the variable address pin A0. The hardwired address pins are most likely both zero, unless the manufacturer was ordered to program it otherwise (You can check the address with the scanner example). So, if you wire A0 to ground, the address will be 0b1100000. If you wire A0 to 3.3V, it will be 0b1100001. The direction bit will be handled by the library - you don't have to worry about it.

4.The MCP's data protocol: You cannot simply send the values from the ADC to the DAC. It except's a special data format, which includes command bits to determine it's mode of operation. I think, I have already described how the data is build up in principle and code pretty well in my answer to this question. If there is something special, that you don't understand, you can ask a new question and refer to that answer in it. Also I think, you should use the type unsigned int for the dac_value, since values from an ADC and values for a DAC both are positive only.
Please keep in mind, that building such projects needs some time investment, until you understand, what actually is happening there. If you use any chip, the datasheet of that chip is always a must read. I personally never haven't worked with the MCP4725. I just have read the datasheet. All information is already there.

Excellent description. That you said that the conversion of adc to analog can not be done easily, should the lookup table be used as adafruit examples? Or no?
So the code I wrote is not correct!

I don't know, what adafruit example you mean. Please provide a link. I don't see, where you would need a sine lookup table here, since you are just transmitting the signal from the ADC to the DAC. The DAC will output, what the ADC have read. A sine lookup table is only needed, if you want to generate a sine wave ftom the esp

this example link

I want to reconstruct the DAC  output using ADC value . . . . . . . .

Adc side wave form -->link

To just replicate the analog signal you don't need a lookup table

look this example : link

@navid And what should I see in that example? Also they are using an Arduino (most likely the Uno), not the ESP as you. So most likely you cannot simply use the same library

Ah, I shouldn't be disappointed ..


text:
about how to share one External serial EEprom using two microcontrollers?
strong texti have Vector nav100 IMU sensor that sends data serially UART.I want to receive data from it using ATmega32 and then store data in AT24c1024 EEprom using I2C,then using another ATmega32 to read the saved data on AT24c1024 EEprom using I2C to control a servo motor..so,the AT24c1024 EEprom is then shared between the two microcontrollers...i have serached the internet about how to share one  External serial EEprom,i found that......(On way would be for the two  mcrocontrollers to have an output line as an input to the other. A master that is "using" the EEPROM perhaps pulls his output low (or high - your choice) to say "I'm using it at the moment". The other reads his input first before going near the EEPROM if he finds the line active he backs off until it is set inactive by the other master.i tried this solution but i failed...can any one help me on this solution ?
Thanks in advance......
this is my code
{

    //the first MCU fristly check the pin
    //if high,then write,then set it low to allow read
    //the second MCU fristly check the pin
    //if low ,then write,then set it high to allow write

    //for the MCu that will write
    //first it will check for the pin ,if it is LOW,
    //then it can write data to EEprom
                     DDRA=0x00;//configure portA as input
            if(PINA==0x00)//check for the pin, if LOw,then wirte
    {
        byte_write(data);
        _delay_ms(10);
    //After writing set the pin as high to allow the second MCU to read
        DDRA=0xff;//configure portA as output
        PORTA=0xff;//set the pin as high
        _delay_ms(10);}

    //for the MCu that will read,i set adelay of 10 ms
    // to allow the first MCU to write some data

                         _delay_ms(1000);//delay from the data to be written on the EEprom
                 DDRA=0x00;//configure portA as input
        if(PINA==0x01)//check for the pin, if HIGH,then read
    {
             y=byte_read(data);
            DDRA=0xff;configure portA as output
            PORTA=0x00;//set the pin as high

}

I wonder what the reason is for the EEPROM ... because of temporarily storing data, or as a buffer (timing difference between the writer mcu and reader mcu? Or for other reasons (too)? Otherwise, remove the EEPROM, and send data directly from one MCU to the other (e.g. using UART/SPI/I2C).

@MichelKeijzers to prevent data from loss if the next frame from the sensor came and the microcontroller is still processing the last frame,so the frame will be dropped.

If written correctly, receiving and processing are 2 different things. Also the Wire library does not support multi master. When both controllers try to access the EEPROM simultaneously, the bus will be blocked.

@chrisl OK.that is true..so,.I have searched the internet for that,I have found that On way would be for the two microcontrollers to have an output line as an input to the other. A master that is "using" the EEPROM perhaps pulls his output low (or high - your choice) to say "I'm using it at the moment". The other reads his input first before going near the EEPROM if he finds the line active he backs off until it is set inactive by the other master.I tried this ,but I failed...could me give me pseudo code for this solution?

With what did you fail? You should provide the code in question, so that we can help you with that. Though I'm still not sure, that using an external eeprom is a good idea

@chrisl OK,I will give you the code...but is  there any other way to prevent data from loss?

@chrisl i have connected first pin in portA in both microcontrollers.for the microntroller that will read,i write delay 10ms for the data to be written on the EEprom  DDRA=0xff;
PORTA=0x00;//pin is High
_delay_ms(10);while(1){
for (int i=0;i<10;i++){
DDRA=0x00;
if(PINA==0x01){
y=random_location_byte_read(i,0xA0);
_delay_ms(10);
uart_send(y);
_delay_ms(10);
DDRA=0xff;
PORTA=0x00;

Please include your whole compilable code into the question by editing it. You can format it correctly by selecting it and clicking the {} button

@chrisl i have edited the question and send the code

You didn't show us a complete, minimal, compilable example, so my answer will only cover some important points.

Your indention is way off. It is important to use the correct indention, since it help structure your code and will let you quickly see misplaced brackets. The Arduino IDE even has an autoformat function for this.
You are configuring and checking always the whole PORT A, but you have only connected one of the pins. When you configure the whole port as input (without pullup), the other pins will be floating. Also, if both devices have the pin on input (no pullup), this pin will also be floating. The check cannot work this way. You should only look at the first bit in the port registers, since that is the pin, that you connected. You can set all other bits to zero when reading, by performing a bitwise AND operation: if(PINA & (1<<PA0)). This will execute, when the first bit of PINA is 1. To set a single bit you can use the bitwise OR: DDRA |= 1<<PA0; will set the first bit of DDRA. To erase only that bit from the register, you can use DDRA &= ~(1<<PA0);. The rest of the port will stay untoched with this.
Your current protocol is, that the first MCU will check for LOW, do it' transmission, then drive the pin actively HIGH as a signal for the second MCU to start transmitting. The second MCU will do it's I2C stuff and then drive the pin actively LOW. So now we have an active LOW and active HIGH on the same pin, which in principle is a short. A rather big amount of current will flow from one MCU to the other, most likely destroying at least one of the pins (meaning the output hardware in the MCU, that serves that pin). To avoid this, you can use a principle like that, that the I2C port uses: Open Drain logic. You can start with the first MCU's pin configured as OUTPUT LOW, while the other is INPUT PULLUP. LOW means the first MCU can work. If the first MCU want's the second MCU to do a transmission, it will release the line by setting the PIN to INPUT PULLUP. The second MCU now sees a HIGH level on it's pin and starts it's transmission. When it is finished, it will drive the line actively LOW for a defined duration (enough for the first MCU to react) and then to INPUT PULLUP again. The first MCU will then see a LOW level on it's pin as a signal, that the second MCU is finished. It then itself drives the line actively LOW. Then the play starts again. The important thing is, that a HIGH state is only done by a pullup, not actively driven.

That said, I still don't see the necessity to share an external EEPROM for this use case. You are overthinking the problem. You wrote, that you don't want to miss a frame, if the second MCU is still processing the last frame. There are better ways to do that (especially when you consider the limited lifetime of EEPROM).

You didn't tell us, why you are using 2 MCU's, so maybe your goal can be reached with only 1 MCU, which will eliminate the whole need for transmission.
You could use another UART interface via SoftwareSerial or it's sibling libraries to let the MCU's communicate directly. "Not missing a frame" will still be the case, when you are not disabling interrupts. The library will read the data into a buffer in interrupts, while you are processing the previous frame. Depending on how much data you send, you might want to make the buffer bigger, but that is a simple change in the libraries definitions.
If you want to use I2C to communicate between both MCU's, you have 2 ways of doing it. You can either go the same way as described above for UART, by just letting it fill a big enough buffer, or you can do this through the bus transmissions. The first MCU would be the master, that tries to send the data to the second MCU (slave), when there is new data available. The slave will receive the data normally. When the frame is finished receiving, the slave can leave the bus, until it is finished processing. So, when the master tries to send more data in this time, the transmission will fail at the start, since no slave with that address is on the bus (the slave MCU left the bus for this period of time). You can check the return value of Wire.endTransmission(), which will reflect the corresponding error code. If this error code is returned, the master should wait a bit and try to send this frame again, until it is received successfully. That also means, that the master needs a big enough buffer for storing new data, while waiting for the slave to be ready. Or another way: The master can request 1 byte from the slave, that indicates, if the slave is ready for new data. If not, the master will wait a bit and ask again. If yes, it will transmit the data.

Note: Either way the frequency of data reception and processing must be equal for continuous operation. The whole chain will be as fast as the slowest part. If you receive data faster, than it get's processed, the buffer will fill up fast, until you really have to drop frames. The prinicples above are more about the case, when the processing and receiving may misalign or vary a bit, but at the average staying at the same speed. And for this simple communication buffers, that all communication libraries use, with enough space for maybe 2 to 4 transmissions (depending on the variation) are way enough.


text:
Powering Arduino with Thermostat Power
So I want to make an Arduino based thermostat controller. I'm good with the semantics behind this, there's just one detail I want to make sure I get right: Power
I know US thermostat power is 24VAC, but I'm not sure how to convert that to 12V 0.5A DC that the Arduino wants. I'd like to do this efficiently rather than generating a ton of heat in the process, too. I don't even know how many amps "24VAC" is, which is the only specification I can find on thermostat power.
I've found 24VAC to 12VDC converters (made for surveillance cameras) online, but most are rated for 1.5A, and I'd be concerned about frying the Arduino. I am not sure if the Arduino only pulls as much as it needs, or if it would try to pull the full 1.5A and destroy itself. I also do not know if these are relatively power efficient, either.
I'm generally hoping someone has been down this path before so that I don't have to reinvent the wheel.

" I don't even know how many amps "24VAC" is..." That doesn't really make sense. 24VAC isn't any number of amps. The 24VAC transformer is designed for some maximum current load. It's probably got enough extra current capacity to drive a modest 5VDC Arduino project, especially if you provide the 5V using a buck style power supply like the one I suggest in my answer. Those convert one voltage to a lower voltage at very high efficiency.

You should moniter the 24V AC line while the furnace is operating. When we bought our house in 1990, we replaced the mercury switch thermostats with Honeywell units designed to be powered from 24V.  Woke up one night with the house at 88F!  Turns out the furnace turned the 24V going to the thermostats on and off, and that messed up the thermostat, causing it to lose its programming.  Replaced the thermostat with a battery powered unit that controlled a relay to turn the heat off & on. No problems since then.

@DuncanC I know 24VAC says nothing about amperage. I was trying to making a tongue-in-cheek joke about lacking specification. Guess it didn't translate well to text. Oops. Thanks for your full reply! I'll pick up one of those converts and see what I can do.

I don't even know how many amps "24VAC" is

Exactly, because that's a voltage rating (24 Volts AC) and no information about the current capability is given.

I've found 24VAC to 12VDC converters (made for surveillance cameras) online, but most are rated for 1.5A, and I'd be concerned about frying the Arduino. I am not sure if the Arduino only pulls as much as it needs, or if it would try to pull the full 1.5A and destroy itself

The Arduino, as a semiconductor, will consume only the current it needs. What current it needs is determined by the processor core (if it's e.g. in sleep-mode or not), the activated peripherals (ADC etc) and devices powered externally via the Arduino's +5V or +3.3V pins.
The typical power consumption of an Arduino board running a sketch (no low-power mode + no external devices) is about 20mA, aka 0.020A.
Also note that what's happening is when you feed +12VDC into the VIN pin, it goes to a linear voltage regulator, which converts excess voltage into heat while keeping the current the same. The official Arduino Uno (not a chinese clone!) has a NCP1117ST50T3G, which is a 6.5V-20V (recommended limit:12V) to 5V linear regulator with I_out of minimum 1A, typical 1.5A (also note I_out is circa I_in, the regulator itself needs negligable current). Clones might use a cheaper (and worse) voltage regulator. Also note that this output capability might not be realisitically achievable without a heat-sink on the regulator; since excess voltage is converted into heat, converting +12V to +5V at 1A creates (12V-5V)*1A = 7W of heat(power). The package cannot sustain that for very long and the regulator shuts down due its built-in thermal protection.
In short it can be said that it's not a problem to connect a higher-rated power supply to an Arduino. The Arduino will pull what it needs to power itself and everything else on the +5V and +3.3V pins, if it's within the limits of the voltage regulator.
These videos might help your understanding of linear voltage regulators: https://www.youtube.com/watch?v=GSzVs7_aW-Y https://www.youtube.com/watch?v=giGRrODKJSE

If you're just running an Arduino and a few low power components, feeding the Arduino's voltage regulator 12V would be fine. However, if the 24VAC to 12VDC power supply is unregulated, it may well put out more than 12V.
If your Arduino system draws a lot of current from the 5V regulator then it will generate a lot of heat, and might overheat. What else are you driving from the Arduino's 5V and 3.3V lines?
A buck style power supply would be a good choice for this setup.
Here is an example that should work very well:
https://www.amazon.com/SMAKN%C2%AE-Converter-Voltage-Supply-Waterproof/dp/B00RE6QN4U
The picture on that supply says it will work with from 8-35V, so there is a lot of "wiggle room" in its supply voltage. Even if the doorbell draws enough current for the 24VAC to drop to 12VAC while the doorbell is ringing, the supply should still be able to keep the Arduino running just fine.
(You could feed the regulated 5V from that supply directly into the USB input on your Arduino)
That is a very high efficiency supply that will waste very little power as heat. You wouldn't need anything else other than that.

Would it be a bad idea, then, to put the Arduino in line with a 1A fuse just in case?

That would be fine, but an Arduino isn't going to draw 1A unless you have some high current loads plugged into it's 5V line, or if you short something.