text:
The problem of not saving the previous value when sending it from bluetooth
Controlling Led's from Buttons and Bluetooth by same method
The problem now :
the LED light up when you send an A over Bluetooth and it will turn off after 2 sec automatically without you doing anything (this is the wrong now in video).
I Want the same char when send data the led turn on and when i want closed led send same char to turn off light .
The code: bottom this page
thank
this is the wrong now in video

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

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

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

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

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

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

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

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

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

C has an "Exclusive Or" operator which is ^.  You can use that instead of | so that it toggles the bit rather than always setting it:
case 'A' :
    bt_leds_activated ^= 1;
    break;

With ^ if you OR a 0 with a 1 you get a 1. If you OR a 0 with a 0 you get a 0. If you OR a 1 with a 1 you get a 0.
That means every time you send A bit one of bt_leds_activated will invert. If it's 0 it will become 1. If it's 1 it will be come 0.
Also you seem to have two sets of states - the button states, and the bluetooth states. Instead you only want one set of states, and both the buttons and the bluetooth toggle bits in that single state set.
Because of that if either of the methods of turning an LED on has turned the LED on then the other method will have no chance at all of turning the LED off.
So just drop bt_leds_activated completely and use ledstates:
case 'A':
    ledstates ^= 1;
    break;

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

No any that change for project state after edit code. the wrong still .
hey man, please watch video to understand bug . thanks
https://youtu.be/EcpJeewE1AU

I think your problem is that you have two sets of states, when you really only want one.

What is the solution . Can you edit this bug. I think bug in this if condition

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

Forget bt_leds_activated completely. Just use ledstates everywhere.

Edit your answer bro, and then explain for me as example

ledstates |= bt_leds_activated; shift_out(ledstates); bt_leds_timestamp = millis();

How about these lines

I think you aren't completely clear in your own mind what you want to achieve. I have no idea what you are trying to do with those lines.

I want delay time when send char after char

I don't know what that means.

Firstly : thank for edit my code now code run perfectly . But this code is clean code or no .and then for example when send character A by Bluetooth in real The sending process requires a time delay between the sent value and the subsequent 2nd value .

Thanks for you man on your answer for may problem


text:
Measure lipo voltage while powering arduino
I have a arduino pro micro 5V that I want to power with a 3.7V lipo. I also have a charging module to charge the lipo.
(https://www.banggood.com/nl/TP4056-1A-Lipo-Battery-Charging-Board-Charger-Module-Mini-USB-Interface-p-1027027.html?rmmds=myorder&cur_warehouse=CN).

I want to measure the battery level of the lipo.

Should I use a step up module to 5V?

How can I measure it? I read that you can't just use analogRead because the lipo itself is the reference.

Thanks in advance!

Pro Micro uses the '32U4 processor? http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7766-8-bit-AVR-ATmega16U4-32U4_Datasheet.pdf    Maximum Frequency
– 8MHz at 2.7V - Industrial range
– 16MHz at 4.5V - Industrial range  - so you are operating out of spec with 16 MHz crysta;/resonator and  3.7V-4.2V LiPo battery.  The '32U4 has a Selectable 2.56V ADC Reference Voltage, so you can use the Internal Aref voltage (vs the default External setting), divide down the battery voltage to be less than 2.56V max, and measure that way. Results may not be accurate if Vcc is < 5V with 16 Mhz clock.

But if I use a step up converter and a voltage divider I should be able to measure it? How do I have to wire it?

The reference voltage for analogRead should be from the regulated 5V line, not from the unregulated input to the Arduino.
The real problem is that the voltage out of the battery will drop with current load. You're supposed to measure either the unloaded battery, or under a known, controlled load.
You ask "Should I use a step up module to 5V?" The answer is yes, but that's unrelated to your voltage measurement question. An Arduino requires a source of regulated 5V. The internal voltage regulator is a linear regulator that requires somewhat more than 5V as input (7.5V is about right.) You can't power the internal voltage regulator with a single 3.7V lipo battery. You'd need a step-up regulator, and with that, you could bypass the internal regulator on the Arduino (assuming your step-up regulator puts out 5V.)

But better is a step up to 7.5V then?

No, there's no need for that. Step up to 5V, and then feed that into the 5V input of the Arduino. If you step up to 7.5V and feed that into the Arduino's VIN, it will just regulate the already-regulated 7.5V back down to 5V, turning 2.5v to heat.

On one of my projects I cut a USB cable and fed my regulated 5V into the USB input. That way you take advantage of the input switching circuitry on the Arduino.

So I step it up and feed it into the Vcc pin or the raw pin?

Step up your lipo voltage to 5V, cut a USB cable (One with the square end that plugs into an Arduino), and feed the 5V into the red and black wires of the USB cable. Then plug that USB cable into your Arduino. When you do that it feeds the 5V into the Vcc pin, through a switching circuit that intelligently selects between power sources.

Why wouldn't I just feed it to the Vcc? I'm only using one power source.

That's OK, until you forget to disconnect the power supply and hook up a USB cable to update your code and possibly fry the Arduino.

And then I connect the positive wire of the battery with a voltage divider to an analog input and I can measure it?

Yes, although the variable load on the battery will cause the voltage to drop, throwing off your measurements.

source: Stack Exchange

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

sort: votes


text:
What's the relation between arduino standard library and esp8266 library?
Can I only use the Arduino standard library, without touching any esp8266 related header files?
I tried to connect to WiFi , succeeded with ESP8266WiFi.h header, but failed with  Arduino library WiFi.h.
I follow this https://www.arduino.cc/en/Tutorial/ConnectWithWPA WiFi connecting tutorial but the board seems to reboot repeatly (I don't understand the error of course. I know nothing about hardware).
My board is ESP8266 V3 ESP-12N F NodeMcu Lua CP2102

the ESP8266WiFi library is based on the Arduino WiFi library so there are very similar functions so code can be ported between different WiFi libraries for Arduino.

the ESP8266WiFi library has examples in IDE Examples menu

The WiFi shield and an ESP8266 with any of several popular WiFi services firmwares are different pieces of hardware, each of which can provide WiFi services to another device connected to it, such as an Arduino Uno. Their interfaces are different, despite that they could be used to do similar jobs - offloading the WiFi communications from the Arduino - and the two libraries are written to drive each of them, respectively.

Ah I see. That official WiFi.h library is merely for the Arduino WiFi shield "extension" board.

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


text:
What is difference between NodeMCU and esp8266?
Since I have no previous experience in electronics I'm getting quite confused while coming across these two terms ..I'd like to know whether they're the same or different.

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

NodeMcu is the name of the firmware originally for the ESP8266
  microcontroller, with support for the ESP32 microcontroller added more
  recently, that allows you to program these microcontrollers using the
  Lua programming language.
NodeMCU firmware was developed so that AT commands can be replaced
  with Lua scripting making the life of developers easier. So it would
  be redundant to use AT commands again in NodeMCU.

And ESP8266 is one of the microcontrollers supported by the NodeMcu firmware.
From NodeMcu vs Esp32 vs esp8266

In the early days of the hobbyist community's adoption of the ESP8266,
  ESP8266 development boards were marketed with the name NodeMcu and the
  term "NodeMcu" started to be associated more with the hardware than
  the firmware. It is common for people with no interest in the Lua
  programming language to buy "NodeMcu" boards and program them with the
  Arduino IDE, which erases the NodeMcu firmware from the board. To make
  things more confusing, multiple companies marketed boards with the
  name "NodeMcu", but with small hardware differences. Over time, the
  NodeMcu boards became less popular in the Arduino world because the
  similarly priced WeMos D1 Mini came out with the same functionality,
  but in a smaller form factor. Now, the "NodeMcu" name is being used to
  market ESP32 boards as well.

ESP8266 is a microcontroller with WiFi capability. it requires external flash memory and some antenna to work. There are different modules and development boards with this system. Some development boards use basic esp8266 modules and some integrate the chip, flash memory and the antenna on the PCB.
NodeMcu is a development board with esp8266 and a firmware with the same name. On the picture is a NodeMcu development board with an esp-12F esp8266 module soldered to the PCB of the NodeMcu. The development board adds required circuits around the module - boot configuration pull-up and pull-down and enable pin pull-up. On the board is an USB chip to connect the esp8266 to USB and an auto reset circuit to enable the upload tool to put the esp8266 into flashing mode. The 3.3 V power for the esp8266 is converted from the 5 V of USB.

The NodeMcu firmware is a Lua language interpreter and has nothing to do with Arduino, but the NodeMcu development board can be used as any other esp8266 development board.


text:
How can I make YX5300 MP3 player play song in a loop?
I am doing a Christmas project and I have an ultrasonic sensor that detects if a person is In front of it. I want that if someone is in front of it, it lights up LEDs, which it does, and it also has to play a Christmas song, which it doesn't. I tried to make it play the Christmas song but nothing happens. Also the LEDs are only blinking when you put ur hand in front of the ultrasonic sensor. I want it to light up the lEDs for the same amount of time the song is, 28 seconds, and than the lEDS should stop and the ultrasonic sensor should wait for another person and it repeats. I am new to this so please be specific in your reccomendations.
Here is my code:
#define trigPin 10
#define echoPin 13
#include <SoftwareSerial.h>
#define ARDUINO_RX 7//should connect to TX of the Serial MP3 Player module
#define ARDUINO_TX 6//connect to RX of the module
SoftwareSerial mySerial(ARDUINO_RX, ARDUINO_TX);
static int8_t Send_buf[8] = {0} ;
#define CMD_SEL_DEV 0X09
#define DEV_TF 0X02
#define CMD_PLAY_W_VOL 0X22
#define CMD_PLAY 0X0D
#define CMD_PAUSE 0X0E
#define CMD_PREVIOUS 0X02
#define CMD_NEXT 0X01

int red1 = 5;
int red2 = 4;
int green1 = 3;
int green2 = 2;

long lCnt = 0;
unsigned long lStart;

void setup(){
  Serial.begin (9600);
  mySerial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(red1,OUTPUT);
  pinMode(red2,OUTPUT);
  pinMode(green1,OUTPUT);
  pinMode(green2,OUTPUT);
  delay(500);//Wait chip initialization is complete
  sendCommand(CMD_SEL_DEV, DEV_TF);//select the TF card
  delay(200);//wait for 200ms

}

void loop(){
  float duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);

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

  duration = pulseIn(echoPin, HIGH);
  distance = (duration / 2) * 0.0344;

  if(distance > 0 && distance <=60){

    digitalWrite(red1,HIGH);
    delay(50);
    digitalWrite(red2,HIGH);
    digitalWrite(green1,HIGH);
    delay(50);
    digitalWrite(red1,LOW);
    delay(50);
    digitalWrite(red2,LOW);
    digitalWrite(green2,HIGH);
    delay(50);
    digitalWrite(green1,LOW);
    digitalWrite(green2,LOW);
    delay(50);
    sendCommand(CMD_PLAY_W_VOL, 0X1E01);
  }

}

void sendCommand(int8_t command, int16_t dat)
{
  delay(20);
  Send_buf[0] = 0x7e; //starting byte
  Send_buf[1] = 0xff; //version
  Send_buf[2] = 0x06; //the number of bytes of the command without starting byte and ending byte
  Send_buf[3] = command; //
  Send_buf[4] = 0x00;//0x00 = no feedback, 0x01 = feedback
  Send_buf[5] = (int8_t)(dat >> 8);//datah
  Send_buf[6] = (int8_t)(dat); //datal
  Send_buf[7] = 0xef; //ending byte
  for(uint8_t i=0; i<8; i++)//
  {
    mySerial.write(Send_buf[i]) ;
  }
}

Thanks

I think you want to use the command [Single cycle play] which is 7E FF 06 08 00 00 01 EF (the 00 01 towards the end is the song number to play).
All the commands are detailed in the manual.

Where should I put that in my code?

@elimar008 in place of your current play command. You may want to add a set volume command as well.


text:
Mixed structure with int and string
I want to create a structure like this:
 struct commands
{
  int   cmd;
  char  descr[25];
};

commands cmds[] =
{
  {16, "Hammond Organ"},
  {17, "Percussive Organ"},
  {18, "Rock Organ"},
  { 0, "" }                   // end of list marker
};

The compiler doesn't protest, but in a simulator the values of cmds[i].descr are all zeros.
And the line
Serial.write(cmds[1].descr);

prints nothing.
Please recommend how to rewrite the code.
Thanks.
EDIT
Thanks for your answer. It helped me a lot.
There is something wrong with the simulator (Simulator for Arduino - version 1.11E Designed by Virtronics). In the meantime I received the Mega 2560 board and the code works well with the board.

What version of the IDE and avr-g++ are you using? If you enable verbose compilation, you should see the location of the avr-tools (avr-g++, avr-objdump...) and the generated elf file. Run avr-nm -Cn path_to_the_elf_file to see the memory address where cmds is stored, then avr-objdump -s -j .data path_to_the_elf_file to see its contents. Does it look as expected?

Arduino IDE 1.8.10. As I am a beginner, I don't understand the rest of your question.

My issue is now resolved by the answers of VillageTech and VE7JRO.

There must be something wrong with the simulator you're using, because your code works for me (Arduino IDE 1.8.9, OSX, Arduino Uno).
struct commands
{
  int   cmd;
  char  descr[25];
};

commands cmds[] =
{
  {16, "Hammond Organ"},
  {17, "Percussive Organ"},
  {18, "Rock Organ"},
  { 0, "" }                   // end of list marker
};

void setup(){
  Serial.begin(9600);
  Serial.write(cmds[1].descr);
}

void loop(){}

The above sketch produces no errors or warnings using my OS and IDE version.

Same here. Compiles cleanly with -Os -Wall -Wextra and works perfectly with both avr-g++ 5.4.0 (shipped with Ubuntu 19.10) and 7.3.0 (shipped with the Arduino IDE 1.8.10).

Try to use char pointer notation (char *) instead of array notation (char[]) in structure declaration:
struct commands
{
    int   cmd;
    char*  descr;
};

OR -

use struct declaration as-is, but change the array initialization like below:
commands cmds[] =
{
    {16, {"Hammond Organ"}},
    {17, {"Percussive Organ"}},
    {18, {"Rock Organ"}},
    { 0, {""}}                   // end of list marker
};

Additionally, it seems that it always should be written as:
struct commands cmds[] =
{
    // here your code
};

If you have disabled warnings in your compiler, enable them again - and try to write program the way that you will newer receive warnings.
Thanks for your answer. It helped me a lot.
There must be something wrong with the simulator (Simulator for Arduino - version 1.11E Designed by Virtronics).
In the meantime I received the Mega 2560 board and both char pointer notation (char ) and array notation (char[]) work well with the board.
The compiler (Arduino IDE v. 1.8.10) really produces warnings:
ISO C++ forbids converting a string constant to 'char' [-Wwrite-strings].
Perhaps the simulator is more meticulous than the compiler and therefore refuses to work with a code thar generates warnings.


text:
How to use a potentiometer to access data within a 2 dimensional array?
I'm trying to create a 2D array of notes that are split into 3 scales. There are 3 notes in each scale. There are 3 buttons to play each note and I want to use an available potentiometer to select each of the scales to be played.
Despite my searching I cannot understand how to achieve this correctly. So far this is what I have.
Using an Arduino Uno:
// musical notes
int C = 1046;
int D = 1175;
int E = 1319;
int F = 1397;
int G = 1598;
int A = 1760;
int B = 1976;
int C1 = 2093;
int D1 = 2349;

const int numScales = 3;
const int numNotesPerScale = 3;

const int  notes[numScales][numNotesPerScale] = {
  {C, D, E},
  {F, G, A},
  {B, C1, D1}
};

const int numberOfButtons = 3;
int buttonPin[numberOfButtons] = {2, 7, 4};
//int notes[numberOfButtons] = {C, D, E};
int ledPin[numberOfButtons] = {11, 10, 9};

int buttonState = 0;         // variable for reading the pushbutton status
int speaker = 3;                 // name of the speaker key

void setup() {

  for (int i = 0; i < numberOfButtons; i++) {
    pinMode(buttonPin[i], INPUT);
    pinMode(ledPin[i], OUTPUT);
  }
  pinMode(speaker, OUTPUT);     // set speaker to be an output
}

void loop() {
  int numScales = map(analogRead(A2), 0, 1023, 0, 2);
  //int numScales = analogRead(A2 / 341);

  for (int i = 0; i < numberOfButtons; i++) {
    checkButton(buttonPin[i], notes[i], ledPin[i]);
  }
}

void checkButton(int buttonPin, int note, int ledPin)
{
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);

  // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
  if (buttonState == HIGH){
    digitalWrite(ledPin, HIGH);
    tone(speaker, note);                 // play the note
    delay(100);                       // wait for 1/10th of a second
  }  } else {
    digitalWrite(ledPin, LOW);
    noTone(speaker);                  // stop playing the note
  }
}

Which part are you having trouble with? You'll want to handle this piece by piece. Are you able to read the pot? Are you able to play notes?

what is it that you are unable to understand? ... create 2d array, read button status, read pot position, or something else? ... you need to determine what is the actual problem ... nobody can help you until you know what you need help with

I think my pot is not being recognised and that my 2d array is being accessed like a single array instead. This is why I'm not getting any true sequence of notes. My question is how should I take "int numScales = map(analogRead(A2), 0, 1023, 0, 2);" and use it to access the scales?

Using the Arduino map() function seems a reasonable approach to this, however you have a problem with the indexing.
if (numScales == 3); {

Is probably not what you want, as that condition can never be true since you set it to something in the range of 0-2 before you reach this check.
Considering only the relevant dimension, you a 3-element array, which will have legal elements numbers 0, 1, and 2
You call map(analogRead(A2), 0, 1023, 0, 2); which can produce an output in the range of 0-2, so far so good.
But then check for a value 3 which is not only illegal as in index to a 3-element array, but unable to be produced by your code.
Additionally you should probably stop trying to use the numScales variable to do double duty holding both the initial size and later also the current index.  And you should probably pass that as an argument, rather than make it a global variable.
You are also failing to ever use the current scale as an index into the notes array.  The syntax of double array indexing would be notes[x][y] but of course this should only be done with indicies to elements that exist.
It would probably also be a good idea to add some debug output of the internal logic, for example print both the raw ADC reading and the result of mapping that to the selected "scale".

I'm afraid being crap at programming isn't really allowing me to absorb some of these answers correctly. If I remove "int numScales = map(analogRead(A2), 0, 1023, 0, 2);" and uncomment "//int notes[numberOfButtons] = {C, D, E};" then each button will play a C, D or E. This works fine until my decision to add a way of changing scales. Is a 2d array the best way to do this and is this a very difficult issue?

A 2d array isn't unreasonable, use the indexing syntax given in this post and make sure your indicies are legal though.  Maybe first make a version which print out the indicies it would use, but doesn't actually use them.  Experiment with your buttons and knob and see that what it would do is reasonable.  Then add making it actually do it.

You could also flatten an array[x][y] to something like array[x+(3*y)]

The mere mention of reasonableness scares me!!!!

How do I add my updated code for analysis and further comment please?

// musical notes
int C = 1046;
int D = 1175;
int E = 1319;
int F = 1397;
int G = 1598;
int A = 1760;
int B = 1976;
int C1 = 2093;
int D1 = 2349;

const int columns = 3;
const int scales = 3;
int potVal = 0;
const int  notes[scales][columns] = {
  {C, D, E},
  {F, G, A},
  {B, C1, D1}
};

const int numberOfButtons = 3;
int buttonPin[numberOfButtons] = {2, 7, 4};
int ledPin[numberOfButtons] = {11, 10, 9};

int buttonState = 0;         // variable for reading the pushbutton status
int speaker = 3;                 // name of the speaker key

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

  for (int i = 0; i < numberOfButtons; i++) {
    pinMode(buttonPin[i], INPUT);
    pinMode(ledPin[i], OUTPUT);
  }
  pinMode(speaker, OUTPUT);     // set speaker to be an output
}

void loop() {
  int potVal = map(analogRead(A2), 0, 1024, 0, 3);
  Serial.println(notes[2][2]);
  for (int i = 0; i < numberOfButtons; i++) {
    //checkButton(buttonPin[i], notes[scales][columns], ledPin[i]);
    checkButton(potVal,i);
  }
}

void checkButton(int scaleNum, int buttonNum)
{
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin[buttonNum]);

  // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
  if (buttonState == HIGH) {
    digitalWrite(ledPin[buttonNum], HIGH);
    tone(speaker, notes[scaleNum][buttonNum]);                 // play the     note
    delay(100);                       // wait for 1/10th of a second
  } else {
    digitalWrite(ledPin[buttonNum], LOW);
    noTone(speaker);                  // stop playing the note
  }
}

Ok, thank you everyone for your help! Here is the completed and functioning code for anyone that may find it useful. Why is it so hard to upload code on this site?

This code is incorrect.  As previously explained, 3 is not a legal index into a 3 element array.  You must return the maximum of your map function to 2 as it was before, not 3.

Sorry Chris, I keep getting stick for that one but it was pointed out to me recently that doing this creates an even spread across the pot range and in actual fact never produces a value of 3. I had it the old way mapped to 2 using a maximum of 1023 and it creates problems because 1 extends almost right to the end of the pots range and keeps alternating with 2 so no stability. ......."1023/1024 is 2.9999 something and so gets rounded down to 2. Mapping to 0 to 2 would mean that only the very last position would map to 2".


text:
about receiving float on matlab from ATmega32 Avr
****i am using ATmega32 to send float and want to receive it on matlab,i send 4.85 from ATmega32 but on matlab i receive 4.260233679216239e-31...can any one help me..thanks in advance**
**
    //Atmel studio code++++code for sending float from Atmega32
    union abc{ float fo; unsigned long lo; };
 union abc data;
int main(void)
 { usart_init();
 data.fo=4.85;
 while(1) {
for(int i=0; i<=24; i+=8)
{
    uart_send(data.lo>>i); }}}

 //Matlab code for receiving float
s=serial('COM1','BaudRate',9600);
fopen(s);
out=fread(s,1,'single');
 fclose(s);

i found the solution for this problem, i set a header before sending the data from ATmega32,and on Matlab i check the frame ,if it received correctly,i receive the data
//ATmega32 code
    float x =215.5;
    unsigned char *ptrx;
    int main(void)
    {   usart_init();
        //data.fo=12.85;

        ptrx=( unsigned char *) &x;
          while(1)
       {
        uart_send(0xAA);//equals to 170
        for(int i=0;i<4;i++){
        uart_send(*(ptrx+i));}

        x++;}}
    //on Matlab
    s=serial('COM1','BaudRate',9600);
    fopen(s);
     i=1;
    while i<1000
        header =fread(s,1,'uint8');

        if header==170//equal to 0xAA

     out=fread(s,1,'float');
    data(i)=out;

     i=i+1;
        end
     end
    fclose(s);

The binary representation of 4.260233679216239e-31 is 0x0d0a40a3. The
first two bytes (in big endian format) are 0x0d and 0x0a, which
happen to be the ASCII characters CR and LF. These characters, in
tandem, are often used as line terminators. My guess is that
uart_send() is not doing what you think...
I suggest using Serial.write() instead. This way you won't have
unwanted line terminators. And it will also make your problem on-topic
with respect to this site.
Also, do not send the bytes repeatedly, send them only once, on demand.
If you send them continuously, Matlab may catch the serial stream in the
middle of a number, and assemble the bytes in the wrong order.


text:
SIM868 AT+CIPGSMLOC returns latitude and longitude location as 0.000000
I am unable to get any location data from SIM868 module using the command
AT+CIPGSMLOC=1,1
It returns 0.000000,0.000000,2019/12/23,08:50:39

I have internet enabled using AT+SAPBR=1,1 command.
However I get proper location data when I use the command AT+CLBS=4,1
Havent found any relevant info in the AT command Manual v1.10.
I had AT+CIPGSMLOC=1,1 command working correctly on a sim800L module.

Not enough satellites. Take it outside or put it in a window.

AT+CIPGSMLOC command is used to give gsm location which gives a location as soon as internet is connected. This location is very coarse and is believed to be the location of a cell tower. Which means it has no connection with satellites.


text:
Arduino IDE gives elf but does not give hex file
Arduino IDE give .elf file but does not generate .hex file.
Show verbose output during: compilation is already selected.
/Users/username/Library/Arduino15/packages/Seeeduino/tools/arm-none-eabi-gcc/4.8.3-2014q1/bin/arm-none-eabi-size -A /var/folders/_6/5v2q3kbs09b7fhtpnxj_zgt00000gn/T/arduino_build_274647/kuzu.ino.elf
Thanks...

Why do you assume that you should get a hex? Not all boards need a hex.

Hmmm What will I upload it than without bootloader.

You are right @Majenko can you please help how to upload it to board? When I try to upload bin.

Depends what your programmer and the programming program expects.

As I learnt, It does not generate .hex file for some board. If I change board in Arduino IDE it gives .hex file. It is something about CPU. Thanks for your answers

Arduino IDE can generate .hex file. The menu choice is Sketch:Export compiled binary.
Two files are created:
your_sketch_name_.ino.standard.hex
your_sketch_name_.ino.with_bootloader.standard.
The second one contains the basic bootloader as well.
Both are stored in the your_sketch_name directory that the IDE compiles and saves in to.
Edit: If you are using a non-AVR uC, I don't know if the command works - or exists even.

it is not about AVR boards. the command in question contains ARM compiler

The path contains ARM, is that why you imply it is not about the Arduino IDE?

@CrossRoads arm boards, work out without the Arduino IDE, are usually programmed with a bin or elf file, not a hex.

So the question needs clarification then.

I imply that "Export" will not generate a hex file and a 'with_bootloader' hex if the selected board is from a package that doesn't use hex

As I learned, It does not generate a .hex file for some board. If you change board in Arduino IDE it gives .hex file.

Repeating an earlier answer word for word is not very helpful. Please add some useful information of your own or delete the answer.


text:
How to link a computer processor to an Arduinno on a board?
I am completely new to Arduinno, so please forgive if the question is stupid.
Here is the problem: I have a project where I want an Arduino (or similar microchip board) to handle some sensors and actuators. But I need very advanced "artificial intelligence" to handle the data provided by those sensors.
There are two major obstacles for placing this intelligence on the Arduinno, according to my researches.

First, the Arduinno is coded in a language similar to C: I could of course find a way to write the intelligence, but it will be a time-consuming task for the developper
Second, I might encounter a problem with memory: I will store heavy matrix of data, do complicated calculation, and this might be too much for an Arduinno
Third, I read on stackexchange that there are some ways to compile Python code on Arduinno boards, such as the Arduinno Mega. So I can code this intelligence in Python (which is an easy task), and compile the resulting code on Arduinno. However, I will reach a caveat: some libraries I will use will be entirely compiled, and this will take too much memory on an Arduinno (such as the second issue I mentionned)

So I have another solution, but I am not sure if it is state-fo-the-art, or even a feasible solution:
I would like to separate two tasks:

Write an Arduinno code to handle the sensors and create numeric data
Write a Python code on my computer and compile it as an executable file on my computer
Then somehow, I "extract" the processor of my comouter (Intel, by the way) and I plug it on the Arduinno board. The Arduinno sends the data to the processor, and the processor runs permanently the Python file and gives back data

So question:

Is it possible overall?
Was it ever made?
What communication links are good for exchanging data between processor and Arduinno microchip: USB, Serial, Ethernet?
How can I handle the input of the processor, so that it collects data from the Arduinno and then uses it in the Python code?

Get a pi. That should do everything all in one.

It sounds like you need a lot of compute power. You can either put the sensors and AI on one device (and @majenko's suggestion of a Raspberry Pi would be a direction to pursue) or you need two devices, one to manage the data collection - Arduino, perhaps -  and one to do the AI. We don't know enough about your post-processing and AI to make a good recommendation, but, as you already have a PC with Python running on it, an Arduino talking to the PC would be a good start.
You didn't say which Arduino you're considering, but as most people mean "Uno" when the speak of a generic Arduino, I'd just suggest that an Uno is far too under-resourced for the post-processing part of your project, but probably ideal for the data collection. Cross-compiling your Python code for an Uno still doesn't address its processing speed and memory size limitations.
There are, of course, a lot of "Arduino" products, some with considerably more resources, that may approach your needs - I'm thinking of the Arm-based boards, here - but I've no way of evaluating your project needs at that level.
My own first approach would be to use what you have, to start with: an Uno collecting data and sending it to your PC. Once you have something running, you'll understand the needs and issues better and if you still want a stand-alone solution at that point, you'll be much better able to make that choice.

I may handle this case like using pyserial library I just log the data to my laptop and then using python to do your Advance AI code part.

Send the sensor data as a combined String via Arduino serial port.
read it using pyserial library
add a data logging mechanism if you need or parallel process the data you gathered serially by cast them to their own data type.

Hope this may help you.
Thank you

Thank you, I will look out those. A remaining question is: what hardware is needed to run a typical Python script (I don't need the screen of the computer for example, I do need the processor, do I need the GPU?)

@totalMongot I think you can try with some ARM type boards like RPis or Odroid XUs. But in the initial setup, you need a GUI However. About direct flashing the python script to Arduino this will help you>>>> https://arduino.stackexchange.com/questions/49187/running-python-script-using-arduino

Thanks! :) Is it possible to dismantle a computer and take only the core and some USB and serial ports to achieve something similar to the ARM boards, which can communicate with Arduinno? The GUI would be achieved by plugging a computer to the USB port

yes write your python code as try except (for safe the flow of your script) and run the python script as a daemon(Similar to starting an application from the startup sequence) so it will always on working on the background.
I think this link will help you >>>> https://www.instructables.com/id/Raspberry-Pi-Launch-Python-script-on-startup/
"The GUI would be achieved by plugging a computer to the USB port" >> Yeah if there any HMIs or pi display which can able project via USB it's possible.

For AI use there is the K210 based sipeed maix board. Dual core 400MHz, plus an AI coprocessor.

I suggest that you use a different family of processor than the 8-bit AVR chips that are supported  by the Arduino IDE (and please fix your spelling errors, all the double-letter words are very distracting). A good example might the the Teensy 3.2 or Teensy 3.6 offered here  https://www.pjrc.com/  "Version 3.6 features a 32 bit 180 MHz ARM Cortex-M4 processor with floating point unit" Arduino is programmed in C++, see if your code can be exported in C++ and import it into the IDE for compiling for the selected uC.


text:
How to (optimally) fetch a button press?
For my hardware, I need to check if the button was pressed, but I need to do things only once every half a second.
if (digitalRead(pin) == HIGH)
{
    doStuff();
    delay(500);
}
The above does not work, because I have to check other things in the main loop as well.

You should use the millis function (see millis).
Create a variable of type unsigned long and check it against the current time, with some offset.
See also the debouncing example, how to use this function and maybe you want to implement the debouncing too.


text:
Powering the Arduino with a battery and reading the battery voltage
I am trying to display the battery voltage as it is being used to power the Arduino.
I have tried powering the Arduino through the USB and the battery voltage is read accurately when compared to the multimeter reading.
But when the battery is powering the Arduino and being read, it keeps displaying 5.00 V, which it should not be.
Just wondering what might be happening and how I can go about resolving this issue.
I have been trying to research some answers, and came across something about an 1.1 V reference voltage, but I'm not entirely sure what they mean.
Here is my code for reference:
#include <SoftwareSerial.h>
SoftwareSerial BTserial(10,11);

int battPin = A1;

void setup() {
  pinMode(battPin, INPUT);
  BTserial.begin(9600);
  Serial.begin(9600);
}

void loop() {
  int voltReading = analogRead(battPin);
  float volts = (voltReading/204.6);
  BTserial.print(volts);
  BTserial.print(";");
  Serial.println(volts);
}

I am using a 3.7 V Li-po battery. It is connected to A1 and also to Vin.

AFAIK, Arduinos are set up to use their operating voltage as the analogRead reference voltage by default.
So what I think is happening is that you are trying to measure the battery voltage with the battery itself as a reference voltage.
This will, of course, always show "full scale".
You could use a voltage divider to bring the measured battery voltage down to about 1 V (max) and use the Arduino's internal reference of about 1.1 V for measuring.
Note that the 1.1 V internal reference is stable, but not necessarily exactly 1.1 V. You will have to measure it first.

Oh I see! I will give that a try and see what happens! Thanks!

Also, how can I go about using the internal reference?

See https://www.arduino.cc/reference/en/language/functions/analog-io/analogreference/

You need to divide down the battery voltage into the 1.1V max range, and use the Internal bandgap voltage reference for the ADC conversions.
Connect the Battery to VCC, not Vin, you don't want it going thru the regulator.

By "divide down the battery voltage" do you mean with circuitry, such as a voltage divider, or through the code? And what is the internal bandgap voltage reference?

Yes, two resistors, in series between VCC and GND. Connect Ax to the junction.  See the datasheet for more info on the internal source.

connecting the battery to the VCC, means connect to the 5V pin? Is that okay? I read that if you connect the USB while battery is connected to the 5V pin, it could damage stuff.

Maybe. 3.7V into the barrel jack will be overcome by the USB input and the power switching circuit, and USB will be used.

If you want measuring a "battery level" in mAh for example, you must measure Voltage AND Current, so INA219 is a better deal (it is a I2C control).


text:
NodeMCU second HARDWARE serial TX as a debug port
I'm using a NodeMCU board to send commands to my home electricity switching box - using RS485 communication.
For that, I've connected MAX485 TTL-to-RS485 converter module to my TX and RX pins.
Currently, I can see the serial commands (that my program sends via RS485) also on my Serial monitor (in Arduino IDE), because the CH341 on the NodeMCU is bridged to the serial pins of it.
My problem is that if I want to send debug strings to my Serial monitor (like 'time was updated using NTP') - the RS485 bus will get them also.
I found some documentation about second TX pin available that can be used for debug messages, but I have 2 questions:

Will it be a HARDWARE port? I don't want to load another library and deal with software Serial ports.
Is there a way to get its output via the USB cable connected between the NodeMCU and my computer? Or will I have to connect another USB converter externally to that port to get its output into computer?

Many thanks!

Just found now a board ESP-32, which supposed to be very similar to NodeMCU, but has another 2 (one usable) UART ports. Not a solution to my current project, but should be considered in the future for such need.

ESP8266 Arduino core has Serial1 as write only hardware Serial on io 2 as TX. IO 2 is D4 on NodeMcu and Wemos D1 mini.
To use the USB chip of the NodeMcu/Wemos with Serial1 you could wire io 2 (D4) to TX. This would not disturb the flashing mode, because bootloader would still listen on standard Serial pins. I tested it.
And for RS485 adapter swap the Serial to io 13 (D7) as RX and io 15 (D8) as TX with the Serial.swap() command.


text:
High frequency Driver circuit
I'm looking for a 2Mhz 24v 100mA Driver circuit for my Piezo transducer. I am not sure that MOSFET could handle that, if it could there are not much design ideas for the same on internet. And there are high frequency LED driver ICs like LT3598, but I'm not sure about those too. Somebody please help me with this.

For piezo you want an h-bridge really.

Thank you for your replay, but this is for the application of Ultrasonic Humidifier. I wrote program for generating a PWM of 1,7MHz, it is a single polarity waveform, and the Piezo transducer also a single polarity device. So an H bridge is too much and most of the components will not be doing anything at all the time.

Please provide a link to the actual device you are using. Piezo transducers are a capacitive device, and with nothing to allow the capacitance to empty after each charge cycle you will have very poor results. For low frequency (audio) a simple resistor can be used. For high frequency you want something faster at discharging like an h-bridge. If your device has its own circuitry in it then that really changes the whole thing.

https://www.aliexpress.com/item/32854394686.html     here you can find the actual device


text:
An arduino servo radar system
I am trying to make something like roomba. Everything is going perfect. I want to have an ultrasonic sensor mounted on servo motor which rotate it from 0 deg to 180 deg & from 180 deg to 0 deg and the ultrasonic sensor will detect if there is any obstacles ahead. I want to take distance from the sensor. The servo motor rotates perfectly alone but when i tries to calculates the distance by the sensor which is mounted on it. The servo stops rotating. I have seen such type of systems in many projects like obstacles avoiding cars etc but i am unable to solve this problem. Can anybody tell me what i can do to solve this problem.
The code I am trying:
#include <Servo.h>
#define trigPin 2
#define echoPin 3
long duration;
int distanceCm;
Servo myservo;

int pos = 0;

void setup() {
myservo.attach(9);
myservo.write(0);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(9600);

}

void loop()
{
  for (pos = 0; pos <= 180; pos += 1)
  {
    myservo.write(pos);
    //delay(500);
   int distance = calculate_distance();
    Serial.println(distance);
  }
  delay(100);
  for (pos = 180; pos >= 0; pos -= 1)
  {
    myservo.write(pos);
    //delay(500);
   int distance = calculate_distance();
    Serial.println(distance);
  }
  delay(100);
}

int calculate_distance()
{

digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

duration = pulseIn(echoPin, HIGH);
distanceCm = duration*0.034/2;

return distanceCm;

}

Can it be, that it doesn't stop moving, but only moving 1 degree per second? If for whatever reason pulseIn() does not sense a HIGH pulse, it will wait for it, until the timeout has passed, which defaults to 1s. That would make the movement very very slow

change the step size to 15 degrees

Yeah, add a timeout to the pulseIn() call


text:
ESP-01S + Fastled
I am trying to control a WS2812B Led Strip with my ESP-01S board.
It works fine with my ESP32 DevKit board, but the ESP-01S won't do anything :/
I couldn't figure out which 2 GPIO the ESP-01S is using (from the pinout), I assume it's GPIO0 (pin 5) and GPUI1 (pin 2).
I modified the sketch and tried several pin settings but the LED won't react.
any ideas what's wrong?

io 0 and io 2 are on every esp-01 header

and io 1 and io 3 as RX and TX. and io 0 has pull-up on esp-01s


text:
Coding issue with for loop
I have an issue with this piece of code concerning the use of 3 capcitance sensors each outputting a midi note chosen from one of three scales selected with a pot. Regarding the sensors triggering notes and the pot selecting scales, everything is perfect.
However, each sensor will play each of the scale's notes by itself with each finger press. This of course is not what I am intending as each sensor should only trigger its corresponding note. Thanks for any clues and tips!!
    #include <SPI.h>
#include <CapacitiveSensor.h>
#include <MIDI.h>
MIDI_CREATE_DEFAULT_INSTANCE();
// midi notes
int c3 = 36;
int d3 = 38;
int e3 = 40;
int g3 = 43;
int a3 = 45;
int c4 = 48;
int d4 = 50;
int e4 = 52;
int g4 = 55;
int a4 = 57;
int c5 = 60;
int d5 = 62;
int e5 = 64;
int g5 = 67;
int a5 = 69;
int c6 = 72;

/////// code & 2d array for scale selection
const int columns = 3;
const int scales = 3;
int potVal = 0;
const int  notes[scales][columns] = {
  {c3, d3, e3},
  {c4, d4, e4},
  {c5, d5, e5}
};

const int numberOfSensors = 3;
int sensorPin[numberOfSensors] = {38, 39, 40};
/////////

static const unsigned ledPin1 = 22;      // LED pin on Arduino Mega
static const unsigned ledPin2 = 23;
static const unsigned ledPin3 = 24;

int val = 10; // this value is best around "10". works with "multiply"
// and "Threshold" to enable Polyphony!
int Threshold = (0); //Threshold of triggered mp3
int Multiply = (0);  //increases or decreases the overal sensitivity

CapacitiveSensor   cs_2_38 = CapacitiveSensor(2, 38); //Mega sensor pins
CapacitiveSensor   cs_2_39 = CapacitiveSensor(2, 39);
CapacitiveSensor   cs_2_40 = CapacitiveSensor(2, 40);

void setup()
{
  for (int i = 0; i < numberOfSensors; i++) {
    pinMode(sensorPin[i], INPUT);
    Serial.begin(9600); //midi(31250)

    pinMode(ledPin1, OUTPUT);
    pinMode(ledPin2, OUTPUT);
    pinMode(ledPin3, OUTPUT);

  }
}
void loop()
{
  int potVal = map(analogRead(A2), 0, 1024, 0, 3);
  for (int i = 0; i < numberOfSensors; i++) {
    checkSensor(potVal, i);
  }
}
void checkSensor(int scaleIndex, int columnIndex)
{
  static boolean lastSensorHit1 = false;
  static boolean lastSensorHit2 = false;
  static boolean lastSensorHit3 = false;

  bool sensorHit3 = cs_2_40.capacitiveSensor(Multiply) / val > (Threshold);
  bool sensorHit2 = cs_2_39.capacitiveSensor(Multiply) / val > (Threshold);
  bool sensorHit1 = cs_2_38.capacitiveSensor(Multiply) / val > (Threshold);

  Multiply = map(analogRead(A0), 0, 1023, 150, 5);
  Threshold = map(analogRead(A1), 0, 1023, 150, 5);

  long total1 =  cs_2_38.capacitiveSensor(Multiply);
  long total2 =  cs_2_39.capacitiveSensor(Multiply);
  long total3 =  cs_2_40.capacitiveSensor(Multiply);

  int Art1 = total1 / val;
  int Art2 = total2 / val;
  int Art3 = total3 / val;

  if (sensorHit1 != lastSensorHit1)

    if (sensorHit1 && !lastSensorHit1)
    {
      digitalWrite(ledPin1, HIGH);
      MIDI.sendNoteOn(notes[scaleIndex][columnIndex], 127, 1);    // Send a Note (pitch 80, velo 127 on channel 1)
      MIDI.sendControlChange(64, 127, 1);
    }

    else {
      digitalWrite(ledPin1, LOW);
      MIDI.sendNoteOff(notes[scaleIndex][columnIndex], 0, 1);     // Stop the note
      MIDI.sendControlChange(64, 0, 1);
    }

  if (sensorHit2 != lastSensorHit2)

    if (sensorHit2 && !lastSensorHit2)
    {
      digitalWrite(ledPin2, HIGH);
      MIDI.sendNoteOn(notes[scaleIndex][columnIndex], 127, 1);    // Send a Note (pitch 79, velo 127 on channel 1)
      MIDI.sendControlChange(64, 127, 1);
    }

    else {
      digitalWrite(ledPin2, LOW);
      MIDI.sendNoteOff(notes[scaleIndex][columnIndex], 0, 1);     // Stop the note
      MIDI.sendControlChange(64, 0, 1);
    }

  if (sensorHit3 != lastSensorHit3)

    if (sensorHit3 && !lastSensorHit3)
    {
      digitalWrite(ledPin3, HIGH);
      MIDI.sendNoteOn(notes[scaleIndex][columnIndex], 127, 1);    // Send a Note (pitch 78, velo 127 on channel 1)
      MIDI.sendControlChange(64, 127, 1);
    }

    else {
      digitalWrite(ledPin3, LOW);
      MIDI.sendNoteOff(notes[scaleIndex][columnIndex], 0, 1);     // Stop the note
      MIDI.sendControlChange(64, 0, 1);
    }

  lastSensorHit1 = sensorHit1;
  lastSensorHit2 = sensorHit2;
  lastSensorHit3 = sensorHit3;

}

You should have another function to do that sensor checking so there isn't all that cut'n'paste code (which some folks consider bad programming). In your checkSensor() function check which sensor is active and call the new function to process it. I'd probably use a switch/case construct for that https://beginnersbook.com/2017/08/cpp-switch-case/

what does this mean? ... it does not make any sense to me ... each sensor will play each of the scale's notes by itself with each finger press

Thanks for your help. @jsotola...it means that if I keep tapping the first sensor only, i will hear each of the scale's notes, one after the other so I know the problem is to do with the for loop as it keeps cycling around. In fact, all the sensors will do this. I guess I'm not sure how to do that with a seperate function but I will look into it Dougie, thanks

you say keep tapping ... does that mean that you tap the sensor and you hear one note, then you tap again and hear the next note, and so on?

Yes, that is correct. Of course, if I keep my finger on the sensor then I hear the sustain of that note until I take my finger off again

and, that is not what you want? ... you do not want to hear the next note, you want to hear the same note on each tap?

You are correct jsotola. I only want to hear the same note on each tap of the same sensor

Well after more tinkering I found that the one change that fixed everything was simply this (in the if/else statements).....changing MIDI.sendNoteOn(notes[scaleIndex][columnIndex], 127, 1); to MIDI.sendNoteOn(notes[scaleIndex][0], 127, 1); [columnIndex] needs to be a [0], [1] or [2] representing one of three scales in the assigned array. This is fine as I'm writing out the code for a few sensors. However, for 16 sensors I'm going to have to use a for loop ....Thanks for all your help! Here's the full code for anyone who needs it...including some alterations to the leds...
#include <CapacitiveSensor.h>
#include <MIDI.h>
MIDI_CREATE_DEFAULT_INSTANCE();

 int c3 = 36;
 int d3 = 38;
 int e3 = 40;
 int g3 = 43;
 int a3 = 45;
 int c4 = 48;
 int d4 = 50;
 int e4 = 52;
 int g4 = 55;
 int a4 = 57;
 int c5 = 60;
 int d5 = 62;
 int e5 = 64;
 int g5 = 67;
 int a5 = 69;
 int c6 = 72;

const int columns = 3;
const int scales = 3;
int potVal = 0;
const int  notes[scales][columns] = {
  {c3, d3, e3},
  {c4, d4, e4},
  {c5, d5, e5}
};
const int numberOfSensors = 3;
const int sensorPin[numberOfSensors] = {38, 39, 40};

const int ledPin[numberOfSensors] = {22, 23, 24};

const int val = 10; // this value is best around "10". works with "multiply"
// and "Threshold" to enable Polyphony!
int Threshold = (0); //Threshold of triggered mp3
int Multiply = (0);  //increases or decreases the overal sensitivity

CapacitiveSensor   cs_2_38 = CapacitiveSensor(2, 38);
CapacitiveSensor   cs_2_39 = CapacitiveSensor(2, 39);
CapacitiveSensor   cs_2_40 = CapacitiveSensor(2, 40);

void setup()
{
  Serial.begin(9600);//midi(31250)
  for (int i = 0; i < numberOfSensors; i++) {
    pinMode(ledPin[i], OUTPUT);
}
}
void loop()
{
    int potVal = map(analogRead(A2), 0, 1024, 0, 3);
for (int i = 0; i < numberOfSensors; i++) {
    checkSensor(potVal,i);
  }
}
void checkSensor(int scaleIndex, int columnIndex)
{
  static boolean lastSensorHit1 = false;
  static boolean lastSensorHit2 = false;
  static boolean lastSensorHit3 = false;

  bool sensorHit1 = cs_2_38.capacitiveSensor(Multiply) / val > (Threshold);
  bool sensorHit2 = cs_2_39.capacitiveSensor(Multiply) / val > (Threshold);
  bool sensorHit3 = cs_2_40.capacitiveSensor(Multiply) / val > (Threshold);

  Multiply = map(analogRead(A0), 0, 1023, 150, 5);
  Threshold = map(analogRead(A1), 0, 1023, 150, 5);

  if (sensorHit1 != lastSensorHit1)

    if (sensorHit1 && !lastSensorHit1)
    {
      digitalWrite(ledPin[0], HIGH);
      MIDI.sendNoteOn(notes[scaleIndex][0], 127, 1);
      MIDI.sendControlChange(64, 127, 1);
    }

    else {
      digitalWrite(ledPin[0], LOW);
      MIDI.sendNoteOff(notes[scaleIndex][0], 0, 1);
      MIDI.sendControlChange(64, 0, 1);
    }
    if (sensorHit2 != lastSensorHit2)

    if (sensorHit2 && !lastSensorHit2)
    {
      digitalWrite(ledPin[1], HIGH);
      MIDI.sendNoteOn(notes[scaleIndex][1], 127, 1);
      MIDI.sendControlChange(64, 127, 1);
    }

    else {
      digitalWrite(ledPin[1], LOW);
      MIDI.sendNoteOff(notes[scaleIndex][1], 0, 1);
      MIDI.sendControlChange(64, 0, 1);
    }
    if (sensorHit3 != lastSensorHit3)

    if (sensorHit3 && !lastSensorHit3)
    {
      digitalWrite(ledPin[2], HIGH);
      MIDI.sendNoteOn(notes[scaleIndex][2], 127, 1);
      MIDI.sendControlChange(64, 127, 1);
    }

    else {
      digitalWrite(ledPin[2], LOW);
      MIDI.sendNoteOff(notes[scaleIndex][2], 0, 1);
      MIDI.sendControlChange(64, 0, 1);
    }

  lastSensorHit1 = sensorHit1;
  lastSensorHit2 = sensorHit2;
  lastSensorHit3 = sensorHit3;

}````````

I am just learning this program so I could be way off on this and I apologize if I am.
Instead of the loop inside of void setup() initialize each pin individually. Also you are telling the system to start the MIDI and set the pinMode 3 times.
Inside the Void checkSensor function you set all the sensorHits every time the function runs, you might save a little bit you do lastSensorHit(i).
I just noticed you have the if command running this function as (int i = 0; i < numberOfSensors; i++).  You don't have a sensor 0, so you might want to change that to (int i = 1; i < numberOfSensors+1; i++)// or just change it to 4.
Inside the function checkSensor, it doesn't look your variable val has a value.
if (sensorHit1 != lastSensorHit1) this is still under the same function as before and it is going to run once per channel that you specified in the controlling if function.
Maybe move this into the void loop() or create its own function?

Thanks Jeff A...you've made some interesting points. I'll have a chance to work again with this later tonight and will report back with my progress!

Thanks for your help everyone but this is way above my head I'm sorry to say. I need to go and learn about all the processes taking place within this code so that I can approach it better .

I hope you can get it figured out.  Good luck and Merry Christmas

Absolutely!! Merry Xmas to you too Jeff A

AWESOME, good job.  To make it easier to read can you put ```` at the beginning and end of your code, it will make it easier to read.  Its the key to the left of 1

Yes, I can never get to grips with posting on this forum. I'll edit that now!


text:
SIM7600 A-H not responding directly when connected through pins
I am working on a project which utilizes three components:

Arudino Pro Mini(5v)
Breakout SIM7600 A-H from AND technologies
9V Battery (connected to RAW and GND on the Arduino board)

I am trying to communicate through the device using the pins provided on the SIM board, which unfortunately is not successful.
I am able to connect to the board directly using an usb-c cable. After installing the right drivers, I am able to communicate with the board using AT commands from my Windows PC.
However, I want to be able to send AT commands through the arduino. The set up looks like this:
I connect the following pins of arduino mini and SIM 7600A-H.

SIM 7600 TXD --> Arduino Pin 2
SIM 7600 RXD --> Arduino Pin 3
SIM 7600 Supply -->  5V
SIM 7600 GND -->  GND

The code that I am using, I tried it with every possible baud rate:
#include <SoftwareSerial.h>

SoftwareSerial mySerial(2, 3); // RX, TX

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(115200);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.println("Goodnight moon!");

  // set the data rate for the SoftwareSerial port
  mySerial.begin(115200);
}

void loop() { // run over and over
  if (mySerial.available()) {
    Serial.write(mySerial.read());
  }
  if (Serial.available()) {
    mySerial.write(Serial.read());
  }
}

After sending an AT command, there is no response, the module has both LED's on, indicating that it is up and running.

please describe the 9 V battery

First a warning: Have you read the datasheet from the link above. The TX and RX pins of the SIM 7600 are 3.3V and your mini is a 5V one. The worst case scenario is that the mini killed the RX pin hardware. The best case failure scenario is that the SIM TX Pin has not enough volts to safely signal a HIGH Level to the mini RX pin.

If you powered the SIM over the VCC of the mini then you have only 150mA current available (for the mini and the SIM module). That would be a problem. The SIM module needs a peak current of about 2A (I got the value from other forums, I found no reliable specification).  That is not drawn for a long time only for sending. But I fear the 150 mA would also not suffice for the standby mode.

If you could connect over USB you know the Baud rate to the SIM module. The Baud rate of the mini's connection to the PC  must be set to the rate that you selected in the Arduino IDE or the Serial Terminal you use. There is no need to try out others.

About your code: I personally would move the mySerial.begin(115200); right below the  Serial.begin(115200);. Just to keep and see them together. The while (!Serial) { statement could be a problem. As written in the comment beneath the statement, it is only necessary for native USB connection but on a pro mini you have a 328P MCU that is connected to a USB to Serial converter and not to a native USB. Perhaps it blocks and your code is not executed.

Sorry for the late response and thank you so much for your thorough answer! I took your advice but unfortunately no success! I have implemented a level logic converter, and changed the code. I checked and the right voltages appear for both the module and the board. The module still does not respond although it works when connected through usb

Is your issue resolved? If not...
I'm using the same module and having the same problem.
Jump the resistors on the R and T pins on the module, they seem to be introducing high impedance on the line. After doing that on my module, the UART worked.
Now my problem now is the module is sending some weird characters, maybe my baud rate is not same or etc, still under investigation.

After further investigation, use shorter wires or connections between your module and arduino or mcu.

The SIM7600 UART interface works with 1.8 levels:

I'm guessing that the AND board has a level shifter from 3.3 to 1.8 to work with the 7600. Since your Arduino Por Mini is a 5V board your UART levels must be at 5V too, try adding a voltage divider to bring down the UART to 3.3V.
Also try lowering the SIM7600 baudrate, the software_serial library doesn't work good with high speeds.


text:
Serial doesn't initialise on Arduino Mega 2560 when not powered via the USB port
I am working on a project with a Mega 2560 and a Sim800L module.
Everything works fine, however if i don't connect the USB port (at least once) and power only externally (either by Vin unregulated 7-12V or 5V regulated pin)
the program will seem not to initialize serial in setup().
I found this which is related to the issue but not a proper workaround:
https://forum.arduino.cc/index.php?topic=24642.0
edit: I can confirm using a resistor to short pins 0+1 together (serial) works but it is not a proper solution. This means you have to disassemble your project to access the resistor or add a switch if you want to use USB to debug later or upload new code. Another workaround which i need to test is to remove all Serial code (because i can in my specific project), but again this is not a proper solution.
Any ideas please?
edit2:
for comments
if(SIM900.available()>0){
// AT command to set SIM900 to SMS mode
SIM900.print("AT+CMGF=1\r");
delay(100);
// Set module to send SMS data to serial out upon receipt
SIM900.print("AT+CNMI=2,2,0,0,0\r");
delay(100);
textMessage = SIM900.readString();
textMessage.toUpperCase();
Serial.print(textMessage);
delay(10);
}

if(textMessage.indexOf("SET PHONE")>=0){
// Set phone number to receive notifications
phoneNumber = textMessage.substring(9,21);
Serial.println("Phone number set to: " + phoneNumber);
String message = "Notification number set to: " + phoneNumber + "\nSend 'Help' for additional commands.\nNote in case of reset number returns to hardcoded default";
sendSMS(message);
Serial.println("Confirmication of phone number change sent");
textMessage = "";
}

so why the softwareserial tag? Sim800 is on Serial1/2/3? do you use some old AVR core version or IDE?

That link is 13 years old and I did not hear about that pin 0/1 trick recently. Do you have such an old Arduino board? Are you sure the USB controller (ATmega16U2 ?) does not get its Vcc HIGH via Vin?

You did not provide any code, so we have to guess. Do you print to the Serial Terminal on your PC/Laptop in the Sketch. The if you don't connect the Arduino with the PC you do not establish the serial connection to the terminal. Perhaps you added a blocking command, that waits for the connection.   Connecting Pin0 and Pin1 simulates the Terminal connection and the blocking code does not block. If I'm right, a solution would be to remove the blocking code. But I don't know code, so I can't tell you how,

@juraj Because i use softwareserial to connect to sim800. I converted it to hardware serial as a test and it works but needs some more changes

@DataDiffler My board is not old, i can check if that's the case

@Peter Paul Kiefer Yes i print without checks. Some parts of the code in loop work so it doesn't make sense for me to need checks. In fact the part that doesn't seem to work checks for softwareserial buffer, not serial so i don't think there is any blocking. Here's an example of the non-working part of the code (didn't debug if both of the blocks don't work):

I would be more interested in the setup method. Where the Serial.begin  is located and all location where Serial is used. Perhaps a while ( ! Serial.available() ) or something else. Can you switch the onboard LED to ON in the first if block above, to see if it is entered at all. And the Software serial can also stop the program and wait for a connection.

Nothing special other than setting initial values and pins, just Serial.begin(57600);  and  SIM900.begin(57600);. I could use while (! Serial); everytime i want to print but i believe this doesn't work on Mega, right?

@DataFiddler Checked (i have 2 here) both are clones using the C340G instead of ATmega16U2 for UART to USB and it is powered normally. Problem is that if i have serial.print functions seem to make the program not able to function normally unless serial is connected. Functions inside the program that don't have serial.print code in them (like sendsms function) work normally and the loop continues to work.

never use SoftwareSerial on Mega (it is not the cause of your problem, only something that doesn't make sense)

the ATmega2560 doesn't know if USB is connected. it sends the data and doesn't care what happens with it. there is no UART flow control to block the transmitting.

@juraj yeah i already converted it today to use hardware serial, i just used software serial since i knew it should work 100%. I know mega2560 doesn't know if usb is connected but i don't know why serial.print will break the program if it's not connected to anything. They say it's because the RX0 pin is floating when not connected. So is there is a way to keep serial.print inside the code and ignore it when not connected?

I think i know a bodge solution..wire the DTR pin into one of the digital inputs and read it when i want to print in serial..

RX and TX of ATmega2560 is connected to the USB chip's RX and TX and this connection is active. no floating pins

@Juraj After doing several checks with Serial disabled and running functions to check if DTR is open or closed i found the issue wasn't caused by this. Posted explanation and answer below!

Ok i found the issue and the solution.
For some reason it seems that while the MCU is running Setup(); hardware or software serial don't work properly.
In my case i have code that set the SIM module to SMS mode and to send those messages to the serial port.
For some reason it doesn't send them (or probably the module is not ready to accept them).
Connecting the USB cable reset the arduino and run setup() when opening the serial monitor setting the module in the correct mode.
Adding this code in the main loop solves this issue even though i have them powered both by the same step down converter.
edit: That turns out 1 hour later after debugging more is not exactly a proper solution to the issue.
 That command to set into SMS mode only works when you are connected to the network.
I have a check for that and a reset function.
So now at Setup() i wait 10s for the module to boot up so it is ready to open a serial port, then i check if it is connected to the network before i send the commands to set into SMS mode.
Example:
// Initializing serial commmunication
Serial.begin(57600);
delay(10000);

while (ini){
    Serial3.begin(57600);
    delay(1000);
    Serial3.print("AT+CGREG?\r");
    delay(100);
    netStatus = Serial3.readString();
    if (netStatus.charAt(22) == '5' || netStatus.charAt(22) == '1') {
         digitalWrite(LED_NET, HIGH);
         ini=false;
         }
    else {
        digitalWrite(LED_NET, LOW);
        digitalWrite(resetPin, LOW);
        delay(2000);
        digitalWrite(resetPin, HIGH);
        delay(30000);
        }
}
  Serial.print("SIM800 ready...");

  // AT command to set SIM800 to SMS mode
  Serial3.print("AT+CMGF=1\r");
  delay(100);
  // Set module to send SMS data to serial out upon receipt
  Serial3.print("AT+CNMI=2,2,0,0,0\r");
  delay(100);


text:
about receiving float on Atmega32 from matlab
I want to receive a float on Atmega32 from matlab. I display the output on an lcd, but i receive 0.000, can any one help me? Please ...
matlab code
s=serial('COM1','BaudRate',9600);
fopen(s)
fwrite(s,170,'uint8');//header frame
fwrite(s,1.2,'float');//the data to be sent

ATmega32 code
union {
  signed long l;
  float f;
} data;

int main(void)
{
  DDRA=0xff;//for LCD
  DDRB=0xff;//for LCD
  data.l;
  char value[8];
  usart_init();
  Lcd8_Init();

  while(1)
  {
    if(uart_receive()==0xAA)
    {
      //header,0xAA=170
      Lcd8_Set_Cursor(0,0);
      Lcd8_Write_String("Float");
      _delay_ms(100);

      data.l=(long)uart_receive();
      data.l=(long)(data.l||(uart_receive()<<8));
      data.l=(long)(data.l||(uart_receive()<<16));
      data.l=(long)(data.l||(uart_receive()<<24));

      dtostrf(data.f,8,3,value);//convert float to string

      Lcd8_Clear();
      Lcd8_Set_Cursor(0,0);
      for(int i=0;i<8;i++) Lcd8_Write_Char(value[i]);
   }

}}

I would say you wrote the value into the long member of data data.l, but you tried to convert the float member of data data.f to a string. data.f is still 0.0

data.l contains the float value sent from matlab..so how to convert data.l to float?

You send a float value from mathlab byte wise to the AVR and store 4 bytes of the float value into a long variable of the AVR. That's complicated, becaus you have to know several things. How is the structure of a float in matlab? Is this the same on a AVR? I would suggest you send a String with the value from mathlab to the AVR and on the AVR convert the string into a float. (I know atof() for this reason. You use an AVR lib I don't know. In matlab you can use the fprintf function to convert the float to a string and send it to the AVR.


text:
arduino uno freezes
Is there a reason why my Arduino Uno freezes after a few minutes of running with power coming from a usb cable connected to my pc?
#include <GY6050.h>
#include <Wire.h>
#include <VarSpeedServo.h>

#define angle1 20
#define angle2 90

#define Sensor_BL A0
#define Sensor_BR A1

VarSpeedServo servo;

GY6050 gyro1(0x68);
GY6050 gyro2(0x69);

int X = 0;
int Y = 0;

int y1_axis = 0;
int y2_axis = 0;

int sensorBL;
int sensorBR;

int speed = 0;
int angle = 0;

int prev_y1_axis = 0;
int y1_hold = 0;
unsigned long timer;
int start = 1;
byte step = 0;
String steps , laststep;
int freq;

void setup() {
  Serial.begin(9600);
  Wire.begin();
  gyro1.initialisation();
  gyro2.initialisation();
  delay(100);
  servo.attach(8);
  servo.write(90);
}

void loop() {
  y1_axis = gyro1.refresh('A', 'Y');
  y2_axis = gyro2.refresh('A', 'Y');
  sensorBL = analogRead(Sensor_BL);
  sensorBR = analogRead(Sensor_BR);

  //0 right - 90 centr - 180 left

  if (sensorBL > 250) {
    speed = map( sensorBL , 0 , 1023 , 0 , 255);
    if (sensorBL < 700) { //less pressure 90+20=110
      servo.write(95 , speed);
      angle = 95;
    }
    else if (sensorBL > 700) { //more pressre 90+90 = 180
      servo.write(105 , speed);
      angle = 105;
    }
  }
  else if (sensorBR > 250) {
    speed = map( sensorBR , 0 , 1023 , 0 , 255);
    if (sensorBR < 700) {
      servo.write(95 , speed);
      angle = 95;
    }
    else if (sensorBR > 700) {
      servo.write(105 , speed);
      angle = 105;
    }
  }
  else if ((start == 0 || millis() - timer > 800) && y1_axis > -90 && y1_axis < 20 && y2_axis > -90 && y2_axis < 20 && sensorBL < 10 && sensorBR < 20) //flat dead end no servo movement - center position - can we separate on different lines the pressure sensor and accell so that I can set the dead end value separately for the press sens and acc ?
  {
    servo.write( 85 , 15);
    //Serial.println("Servo goes to zero");
    start = 1;
    step = 0;
    angle = 0;
    steps = "0";
  }
  else if ((y1_axis < 60 & y1_axis >40) && (step == 0 || step == 2))
  {
    step = 1;
    steps = "1";
  }
  else if ((y2_axis < 55 & y2_axis > 40) && (step == 0 || step == 1))
  {
    step = 2;
    steps = "2";
  }

  if (!steps.equals(laststep)) {

    if ((step == 1 || step == 2) && millis() - timer <= 700) {
      if (freq > 1) {
        servo.write(70 , 20);
        angle = 70;
      }
      else {
        servo.write(78 , 20);
        angle = 78;
      }
      freq++;
    }
    else if ((step == 1 || step == 2 && millis() - timer > 750)) {
      servo.write(78 , 20);
      angle = 78;
      freq = 0;
    }

    timer = millis();
  }
  //Serial.println("Y1: " + String(y1_axis) + " Y2: " + String(y2_axis) + " S1: " + String(sensorBL) + " S2: " + String(sensorBR) + " Millis: " + String(millis() - timer) + " Step: " + String(steps) + " Last: " + String(laststep) + " Angle: " + String(angle));
  Serial.println("Millis: " + String(millis() - timer) + " Angle: " + String(angle));

  laststep = steps;

}

I am using the pc usb power cable to power on the arduino and 2 accelerometers and one SG90 hobby servomotor. Would the best way power on the 1 servo with its own power supply ?
What power supply would you suggest for 1 servomotor?
When not connected to the pc, I use 9v battery to power on together the arduino and the one servomotor
thanks!

It is the part of the code for moving forward and backward in this locomotion system I came up with
https://github.com/marcob2178/Arduino-Based-Game-Locomotion
https://www.youtube.com/watch?v=OYTlF2GhXpQ
Sensors are mounted on shoes

what does it do when it is working correctly?

Is it possible the servo motors draw too much current?

Is your 9V battery a 9V block battery? If yes, you should move to a different battery type, since 9V block batteries are meant for low power applications. They cannot provide much current and any motor (a servo is also a motor) can draw loads of current (especially when stalled)

yes, it is a 9v block battery. Would a 6AA 9V Battery solution be enough to power the arduino uno or mega + 2 accelerometers + 1 servo motor ?

You haven't said or shown how your servo is powered but both the Arduino power supply is limited and your computer's USB power has a protective limit. You can power an SG90 hobby servo from the Arduino, but any larger servo needs its own supply, with only the PWM signal being taken from the Arduino. If the servo (or any other device or collection of devices) exceeds the capabilities of the Arduino's power supply, its output voltage will fall. One of the consequences of that is that the MCU stops. Or if your computer's USB supply is exceeded, it will shut down protectively.
My guess is you're powering your motor from the Arduino and it's starving the MCU.


text:
How to burn bootloader and upload sketches on custom arduino?
Ive turned a project I breadboarded with arduino and other modules into one pcb on EAGLE. The pcb includes the ATMEGA328p smt version that doesn't have the bootloader installed. My question is then what module or components can I use to burn the bootloader onto the atmega and upload programs to it together?

Sidenote; a bootloader isn't always required. I never used it in my projects. I program my sketches directly via ISP. The bootloader is only there so you can program the chip over Serial (over USB).

when laying out a pcb you may wish to include a 6-pin ISP connector for programming the part, either with ArduinoISP or a programmer like the USBASP.

You can use a second Arduino as a standalone programmer for it, either to upload your sketch directly, or to upload a bootloader (after which you'd upload your sketch in the normal way). The example program, ArduinoISP, uploaded into the second Arduino is what can do this. Here is a link to a how-to article for doing just that.
If you haven't already populated your PCB, good - sometimes your external (to the MCU) circuitry can interfere - but it's worth a try, even if you have.


text:
How to count positive electrical pulses?
I have a device that has one blinking LED.
I want to count the number of blinks. I planned to do it using Arduino. I will connect two terminals of LED input to Arduino digital input pins, and I will count the number of positive voltage pulses
I just want to know if it is possible? and if yes then can you please hint the code for the same?

be aware that an LED can be turned on by applying Vcc to the LED, but it can also be turned on by applying 0 V ... it all depends how the LED is connected in the circuit

Look in the Arduino IDE.  There is an example called "State Change Example"  That's what you need.

Trying to use the voltage over the LED might not work, because it only changes from 0V to the forward voltage of about 2V (+/- some tenth). Use jsotola's comment and use the side that gets switched, this could as well be at the current limiting resistor.

You should not count the number of pulses, but the number of transition from 0 to VCC volts or VCC to 0 volts (called rising resp. falling edge).
If you don't want to solder, you can also use a light dependent resistor (LDR) very close by the LED to measure the difference in brightness. See also chrisl's remark below.
The counting you can do manually (in a loop, check as often as possible or needed), or by setting up a timer to check for either rising or falling edges.
I will give the pseudo code so you can figure out the actual code:
bool _ldrPin;
unsigned long int _counter;

setup()
{
   // Set Serial
   Serial.begin(9600);

   // Set LDR
   setAnalogPin(X, INPUT);
   _ldrPin = readAnalog(X);
}

loop()
{
    if (!_ldrPin && readAnalog(X) == HIGH)
    {
        // Rising edge, increase counter
        _counter++;
        Serial.Write(_counter);
        _ldrPin = true;
    }
    else if (ldrPin && readAnalog(X) == LOW)
    {
       // Falling edge, reset status
        _ldrPin = false;
    }
}

There is no "light diode resistor". I think you mean a light dependent resistor. Though I wouldn't suggest an LDR for blinking measurement, they are rather slow. Depending on the blinking frequency this could very well be too slow. A photo transistor is a better choice (a phototransistor is basically a diode in reverse, which get's conductable by light), it can work very fast.

Sir, I am planning to solder. But I think I have to solder both the wires from the led. I thin voltage difference is relative, so how do I compare the difference between voltage(when LED glows) using digital pins.

@chrisl Thanks for the notification (I mean indeed light dependent resistor). I never tried a photo resistor (added your name, upvoted your comment).

@SSR At least both wires should be connected to something otherwise you don't have a (closed) circuit, at least not with the LED in it. For comparing you might use an opamp but that's probably worth a different question.

Detecting the LED Pulses
You want to detect each LED pulse. For this you will need edge detection code. There is an Arduino example built into the IDE and information describing the function here: https://www.arduino.cc/en/Tutorial/BuiltInExamples/StateChangeDetection
To add to the Arduino explanation, you can either detect the rising edge (ie. the transition from a LOW to a HIGH) or the falling edge (ie. the transition from a HIGH to a LOW). I personally prefer the following code to detect a rising edge. In simple terms the code can be translated to this:
if ( (lastLedState == LOW) && (ledState == HIGH) )

where ledState would be assigned by a digitalRead and lastLedState would record the value of ledState at the end of the loop function (ie. just before it reads in the led states again).
Full Code
Now if we optimise the above statement and put it into context:
unsigned long int pulseCounter = 0;
const int LedInput = 3;    // Digital input 3
bool ledState = 0;
bool lastLedState = 0;

void setup() {

}

void loop() {
    ledState = digitalRead(LedInput);

    // If the LED turns ON
    if (ledState && !lastLedState)
    {
        // Increment your counter
        pulseCount++;
    }

    // Update LED flag
    lastLedState = ledState;
}


text:
LCD connection problem
First of all, i have some problems with an lcd .
For a better understanding, the lcd datasheet could be found here:
https://www.mikrocontroller.net/attachment/53098/DGF-12232-S1FBLY-325-17231-1006.pdf
i want to connect it to arduino mega but it has 20 pins and i can't figure it out how it should be connected.
Could someone help me ?

Looks pretty much like any other graphic LCD, so I'd start with that.

This display has a very old (20 year+) SED1520 display controller that is not really suited for low pin count microcontrollers like the Arduino. It needs a full parallel 8-bit data bus  and some (5) control signals, so you will need ~13 pins to connect it to your Arduino. It's not supported by common Arduino libraries so you would need to write your own low-level software to get it to display something. Frankly I would not bother and just buy a better supported (OLED or small TFT) I2C or SPI display instead.

For those reading this answer prior to acquiring an LCD for an Arduino project, consider using a more common alpha / numeric LCD rather than a graphic LCD or GLCD.  Likely there will be more examples to follow as well as more software with more community support.
The linked to Graphical LCD (or GLCD) uses a SED1520 controller.  Searching the Arduino community resulted in finding this openGLCD project.  There may be others.  Looking here (near the end of 2019) we see the comment "added custom sed1520 init routine to fully initialize sed1520 chips" next to the sed1520_Device.h file.  Likely this project supports GLCD modules which use the SED1520 chip.
With regards to wiring GLCD module, on page 19 of the specifications linked to in the question, the table in section 5.1 lists the description of the 20 GLCD pins.


text:
Low power error with serial connection
So I want to create an application where I can send data with a SIM-Module, and when it's not needed it should fall into a "standby-mode" because it's battery powered. But I always get this exact output, and I have no clue why:

wakeup condition fulfilled
Tes

When it wants to print out "Testing ..." it always stops after three letters.
Here's my code:
/*
 *  PINOUT:
 *
 *  UNO >> SIM800L
 *  RX (8) >> TX
 *  TX (9) >> RX
 *
*/

#include <BareBoneSim800.h>

BareBoneSim800 sim800("hologram"); //APN of the carrier

void sendData(char *url)
{
  sim800.enterSleepMode(false);
  Serial.println("Testing GSM module For GPRS Connectivity");
  delay(8000); // this delay is necessary, it helps the device to be ready and connect to a network

  Serial.println("Should be ready by now");
  bool deviceAttached = sim800.isAttached();
  if (deviceAttached)
    Serial.println("Device is Attached");
  else
    Serial.println("Not Attached");

  // Connecting the the GPRS APN Network
  Serial.println(" Connecting to APN");
  bool netConnect = sim800.gprsConnect();
  if (netConnect)
    Serial.println("Connected to Network");
  else
    Serial.println("An Error Occured");

  if (netConnect)
  {
    Serial.println("Making HTTP Get Request");
    String result = sim800.sendHTTPData(url);
    Serial.println("Received Info: ");
    Serial.println(result);

    Serial.println("Current time utc+0: ");
    Serial.println(sim800.getTime());
  }

  sim800.closeHTTP(); // disconnect from server
  sim800.gprsDisconnect();
  sim800.enterSleepMode(true);
}

void wakingUp()
{
  //hardware interrupt measurement goes here
}

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

  while (!Serial)
    ;

  //Save Power by writing all Digital IO LOW - note that pins just need to be tied one way or another, do not damage devices!
  for (int i = 0; i < 20; i++)
  {
    if (i != 8 && i != 9 && i != 2)
    {
      // pin 2 is for waking the arduino up from deep sleep

      //pin 8 and 9 are used to connect with the sim module,
      //these pins must be exluded from power saving
      pinMode(i, OUTPUT);
    }
  }

  attachInterrupt(0, wakingUp, FALLING); //interrupt for waking up

  /*
      various flags for turning stuff down when not needed
based on this very good tutorial https://www.youtube.com/watch?v=urLSDi7SD8M

  */
  //SETUP WATCHDOG TIMER
  WDTCSR = (24);      //change enable and WDE - also resets
  WDTCSR = (33);      //prescalers only - get rid of the WDE and WDCE bit
  WDTCSR |= (1 << 6); //enable interrupt mode

  //Disable ADC - don't forget to flip back after waking up if using ADC in your application ADCSRA |= (1 << 7);
  //ADCSRA &= ~(1 << 7);

  //ENABLE SLEEP - this enables the sleep mode
  SMCR |= (1 << 2); //power down mode
  SMCR |= 1;        //enable sleep

  //BOD DISABLE - this must be called right before the __asm__ sleep instruction
  //MCUCR |= (3 << 5);                      //set both BODS and BODSE at the same time
  //MCUCR = (MCUCR & ~(1 << 5)) | (1 << 6); //then set the BODS bit and clear the BODSE bit at the same time
  __asm__ __volatile__("sleep"); //in line assembler to go to sleep
}

void loop()
{
  //do nothing, use ISR instead
}

char targetURL[] = "http://www.example.com/restAPI/";

ISR(WDT_vect)
{
  //DON'T FORGET THIS!  Needed for the watch dog timer.  This is called after a watch dog timer timeout - this is the interrupt function called after waking up
  //todo, turn on adc conversion again

  int halfHourCounter = 0; //30 minutes => 225 8sec intervals

  bool wakeUpCondition = (halfHourCounter % 225 == 0);

  if (wakeUpCondition)
  {
    Serial.println("wakeup condition fulfilled");
    //reset counter
    halfHourCounter = 0;

    //ADCSRA |= (1 << 7); // turn analog digital conversion back on

    //... measure data and send it away :)
    sendData(targetURL);

    //ADCSRA &= ~(1 << 7); // disable ADC again
  }
  else
  {
    Serial.println("wakeup condition not fulfilled");
  }

  halfHourCounter += 1;

} // watchdog interrupt

I'm using an Arduino Uno in combination with a SIM800L evaluation board. If I call the sendData()-function without any standby-flags enabled everything works fine. Vice versa if I call just a print function for debugging with all the standby flags enabled

Can your battery provide enough current? You didn't specify, what battery you are using and how it is connected

Right! Sorry I forgot about that. At the moment I'm just using a normal USB-Connection for power and reading the serial port.

It seems, that the Sim800 module is drawing too much current, when you start it again. The voltage drops and the Arduino/Sim800 stops working.
This datasheet of the Sim800 states, that it can draw up to 2A when doing a sending burst. An USB port on a computer can provide up to 500mA and you can draw between 200mA to 1A from the Arduino's 5V pin (depending on the version, that you use: Older Unos can provide 200mA, Uno r3 should be able to provide 1A). If you draw too much current through the Arduino from USB, you will fry the diode for voltage source seletion. Also you can fry the electronics of the USB port, if you draw too much current from it (though normally the port should go into shutdown, if you do that, and work again, if you restart the computer).
You have to provide the Sim800 module with enough power and not through the Arduino. You should choose a fitting battery for this. If you don't want to involve a battery at this point, since you are still testing, you can use an USB phone charger to provide enough current.

Thanks! I'll try it out :)


text:
NodeMCU V3 Serial input results in Fatal exception 9 (LoadStoreAlignmentCause)
I am building a simple telnet style interface for experimental settings on my project. I am getting all the serial output sent to serial (and USB to PC). The code works fine, but if I try to read from Serial or check 'Serial.available()' I will get:

Fatal exception 9(LoadStoreAlignmentCause)

Definition:
bool pridaj_cely(uint8_t source_from=0, uint8_t line_LCD=0);
The code:
bool Vstup::pridaj_cely(uint8_t source_from, uint8_t line_LCD) {
  uint8_t i = 0;
  Serial.println(F("one piece input read"));
  switch (origin) {
    case 0: { //Serial
        int16_t znak = -1;
        while (Serial.available() < 0) {
          Serial.print(F("."));
          delay(100);
        }
        Serial.print(F("Somothing is comming"));
        while (Serial.available() > 0) {
          celok[i] = Serial.read();
          if (i < 12)  i++;
        }
      }
      break;
  }
  return 1;
}

Code of Priojenie:
bool pripojenie(bool force_it = 0) {
  Serial.println(("Beginning connection routine"));
  kolo = millis();
  while (!WiFi.isConnected()) {
    int8_t sieti = WiFi.scanComplete();
    Serial.printf("Search result %X", sieti);
    switch (sieti) {
      case -2:
        Serial.println(("\tSearch begins"));
        WiFi.scanNetworks(1);
        delay(50);
        break;
      case -1:
        Serial.print(("."));
        delay(300);
        break;
      default: //This is the relevant case
        Vstup odpoved;
        Serial.ciara;
        Serial.ciara;
        Serial.printf(("Found %X networks"), sieti);
        Serial.ciara;
        Serial.println();
        for (uint8_t i = 0; i < sieti; i++) {
          Serial.printf("%d: %s, Kanál:%d (%ddBm) %s\n", i, WiFi.SSID(i).c_str(), WiFi.channel(i), WiFi.RSSI(i), WiFi.encryptionType(i) == ENC_TYPE_NONE ? "Otvorena" : "");
        }
        Serial.ciara;
        Serial.println(("\nChose network number:"));
        odpoved.pridaj_cely(0);
        // -------------------Never gets past this one-------
        if ((odpoved.Nacislo10() >= 0) && (odpoved.Nacislo10() < sieti)) {
          Serial.printf(("Zadaj heslo pre %s\n"), WiFi.SSID(odpoved.Nacislo10()).c_str());
          String heslo = Serial.readString();
          Serial.print(F("Dostal som "));
          for (uint8_t i = 0; i > heslo.length(); i++) Serial.print(heslo[i]);
          Serial.println();
          Serial.printf(("Vybral som možnosť číslo %d a sieť: "), odpoved.Nacislo10(), WiFi.SSID(odpoved.Nacislo10()).c_str());
          //WiFi.begin(WiFi.SSID(odpoved.Nacislo10()).c_str(), heslo);
        } else Serial.printf(("Nesprávny výber %d"), odpoved.Nacislo10());
    }
  }
}

I have commented all the functions that use pins. The source compiles without any problem.
I am adding the result of exception decoder as it did not help me solve it.

Decoding stack results
0x40202a8d: __yield() at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/core_esp8266_main.cpp line 105
0x40202355: Stream::timedRead() at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/Stream.cpp line 37
0x40202392: Stream::readString() at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/Stream.cpp line 240
0x402013b6: pripojenie(bool) at /home/asi/Dropbox/Arduino/hotel_vstup/hotel_vstup.ino line 315
0x40203411: malloc(size_t) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/heap.cpp line 95
0x40204548: umm_malloc(size_t) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/umm_malloc/umm_malloc.cpp line 1685
0x402018d8: ESP8266WiFiScanClass::_scanDone(void*, int) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/libraries/ESP8266WiFi/src/ESP8266WiFiScan.cpp line 296
0x4020141c: pripojenie_samo(unsigned char) at /home/asi/Dropbox/Arduino/hotel_vstup/hotel_vstup.ino line 327
0x402018d8: ESP8266WiFiScanClass::_scanDone(void*, int) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/libraries/ESP8266WiFi/src/ESP8266WiFiScan.cpp line 296
0x40204bb1: std::_Function_handler ::_M_invoke(std::_Any_data const&, int) at /home/asi/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/2.5.0-3-20ed2b9/xtensa-lx106-elf/include/c++/4.8.2/functional line 2073
0x4020197c: ESP8266WiFiScanClass::_scanDone(void*, int) at /home/asi/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/2.5.0-3-20ed2b9/xtensa-lx106-elf/include/c++/4.8.2/functional line 2300
0x4020e5b8: sys_check_timeouts at core/timeouts.c line 368
0x40202957: loop_task(ETSEvent*) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/core_esp8266_main.cpp line 133
0x4020ac9a: __ssputs_r at /home/earle/src/esp-quick-toolchain/repo/newlib/newlib/libc/stdio/nano-vfprintf.c line 233
0x40206938: _printf_i at /home/earle/src/esp-quick-toolchain/repo/newlib/newlib/libc/stdio/nano-vfprintf_i.c line 194
0x4020ac9a: __ssputs_r at /home/earle/src/esp-quick-toolchain/repo/newlib/newlib/libc/stdio/nano-vfprintf.c line 233
0x402034b4: malloc_loc(size_t, char const*, int) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/heap.cpp line 126
0x40204548: umm_malloc(size_t) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/umm_malloc/umm_malloc.cpp line 1685
0x402018d8: ESP8266WiFiScanClass::_scanDone(void*, int) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/libraries/ESP8266WiFi/src/ESP8266WiFiScan.cpp line 296
0x402018d8: ESP8266WiFiScanClass::_scanDone(void*, int) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/libraries/ESP8266WiFi/src/ESP8266WiFiScan.cpp line 296
0x40204738: umm_realloc(void*, size_t) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/umm_malloc/umm_malloc.cpp line 1745
0x402018d8: ESP8266WiFiScanClass::_scanDone(void*, int) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/libraries/ESP8266WiFi/src/ESP8266WiFiScan.cpp line 296
0x4020299c: esp_yield() at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/core_esp8266_main.cpp line 91
0x40202f53: delay(unsigned long) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/core_esp8266_wiring.cpp line 54
0x40201a89: ESP8266WiFiScanClass::scanNetworks(bool, bool, unsigned char, unsigned char*) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/libraries/ESP8266WiFi/src/ESP8266WiFiScan.cpp line 98
0x40203942: uart_write(uart_t*, char const*, size_t) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/uart.cpp line 498
0x4020299c: esp_yield() at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/core_esp8266_main.cpp line 91
0x40202f53: delay(unsigned long) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/core_esp8266_wiring.cpp line 54
0x402015fd: loop() at /home/asi/Dropbox/Arduino/hotel_vstup/hotel_vstup.ino line 460
0x40201410: pripojenie_samo(unsigned char) at /home/asi/Dropbox/Arduino/hotel_vstup/hotel_vstup.ino line 325
0x40204bb8: std::_Function_base::_Base_manager ::_M_manager(std::_Any_data&, std::_Any_data const&, std::_Manager_operation) at /home/asi/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/2.5.0-3-20ed2b9/xtensa-lx106-elf/include/c++/4.8.2/functional line 1934
0x40204ba4: std::_Function_handler ::_M_invoke(std::_Any_data const&, int) at /home/asi/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/2.5.0-3-20ed2b9/xtensa-lx106-elf/include/c++/4.8.2/functional line 2069
0x40201e50: HardwareSerial::setDebugOutput(bool) at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/HardwareSerial.cpp line 79
0x40202a4c: loop_wrapper() at /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/core_esp8266_main.cpp line 125

line 325 is a wrapper function because async scan can only call void function of specific type and calls pripojenie_samo(uint8_t pointless)
Serial Output: (after translation to English)
Beginning connection routine
Search result 3
-----------------------------------------------------
-----------------------------------------------------
Found  3 networks

-----------------------------------------------------

0: VM5070527, Kanál:11 (-55dBm)
1: Virgin Media, Kanál:11 (-74dBm)
2: VM5076233, Kanál:11 (-85dBm)
-----------------------------------------------------

Chose network number:
Instance cleared
one piece input read

Panic /home/asi/.arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/core_esp8266_main.cpp:103 __yield

>>>stack>>>

 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

SDK:2.2.1(cfd48f3)/Core:2.5.2=20502000/lwIP:STABLE-2_1_2_RELEASE/glue:1.1-7-g82abda3/BearSSL:a143020

decode the stack dump of the exception. https://github.com/me-no-dev/EspExceptionDecoder

Added, but I see no relevant  info, just disappointment that chip contains full paths
if I comment-out all the Serial-available() and Serial .read() the rest of the code works

the paths are in a file on your computer. the decoding takes the debug info from the files created at build but not uploaded to MCU

Thanks, but the problem is still here

did the build for decoding match the code that crashed? the stack dump indicates crash in pripojenie(bool)

pripojenie creates instance of an Vstup class (and then calls pridaj_cely on that instance which manages to report one piece input read to serial and then resets as stated above.
The same seem to be hapening if the code reaches Serial.available() or Serial.read() in other functions

I have translated and added function pripojenie, in this case it is called from asynchronous scaning

I have figured it out
There seem to be understandable limitations if what kind of function can be run as a result of asynchronous scanning (which doesn't seem to interrupt running of a loop function)
So if I have used delay(x) or a while loop until there is input on serial, MCU resets after allotted time runs out.
I have re-written code to start function from loop when scan is complete, and it all runs fine now.
I guess Arduino isn't right language for parallel programing


text:
ESP8266 Deep Sleep Wake Up
I am testing esp8266's deep sleep mode. And i have some questions about that.
1- I want to wakeup esp via timer. I did it. I implemented GPIO16-RST connection and this version done.
2- I want to ake up esp with external button too. It means, I will use timer and button to wake up esp8266 same time.
Is it possible and how can i connect  button to RST pin that while GPIO16 has already connected to RST?

The reset pin of the ESP8266 has internal pull-up. Connecting the pin to ground activates the reset of the ESP.
To create a reset button, wire a momentary push button between reset pin and ground. Pushing the button will connect reset to ground, causing a reset of the esp8266.
The io 16 pin is connected internally to RTC, which in deep sleep counts down the time and then sets the pin LOW. If io 16 is wired to reset pin, this resets the ESP8266 to end the deep sleep.
The only way to end the deep sleep of the esp8266 is a reset. There is no conflict between RTC io 16 and a reset button, both wired to reset pin. Both can activate the reset to end the deep sleep.