text:
Power Arduino Nano with OTG cable
I have a project that I am putting an Arduino Nano in an enclosed box that will light LEDs in a pattern. I am planning to power it with a 5 V power brick but I would like to build a way a update the code to the Arduino without needing to disassemble the box.
Could I use an OTG cable with power (OTG Y cable)  to accomplish this? or is there a better way to do this?

It is possible to use a OTG Y cable just plug it into your phone, power cable into the power source and use the third connector to connect  to your PC. (Assuming the PC only gets GND, D+ and D- and battery bank GND, 5V)
It is also possible to reprogram an Arduino with an Android device that has OTG support.
Would save you a bit of hassle.
My Android phone (LG D605) with ArduinoDroid can easily upload code to my Nano and Uno.

I would be programming it with a pc. I was just wondering if I could power it from the OTG cable and still be able to connect it to the pc. The OTG cable has a micro usb, female usb for connection and male usb for power.

USB voltage is below the 6v minimum specified voltage for Vin (on a 5v board).  It might still work to a degree, but beware that what you are recommending is out of spec.  Your reference to OTG has nothing to do with what they poster is talking about, they are proposing what is basically a Y cable, that could be used with something like an Android device, but instead they want to use it with a PC, USB powerbank and the Nano - no Android involved.

@ChrisStratton My bad, I misunderstood the description. I updated the answer.


text:
Unable to upload code on Arduino Nano
My Arduino Nano v3.0 (made by Gravitech US) is behaving in an unexpected manner. Whenever I try to upload a simple Blink program on the board it always give error which is shown below.
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x01
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x01
...

I have another Nano (a Clone) and an Arduino UNO, both of which work perfectly using the same USB cable and PC.
History: When I used this Nano (original) for the first time, it was having some issue related to the FTDI chip. The FTDI USB was locking up on power up. I referred an answer from Arduino Nano 3.0: FTDI USB locks up on power up.  I shorted the pin no. 26 (TEST) and 25 (AGND) on the FTDI chip, and then I was able to use it. I uploaded the Blink program and tested it, which was working fine.
Now, at present (three years later), when I try to upload even a simple Blink example sketch on it, it never succeeds, and gives me the above mentioned error.
I also tried holding the reset button and releasing it when it shows

Uploading...

Another Issue: Sometimes when I just check the continuity on my Arduino Nano just to confirm whether the hardware is okay or not, it gives me unexpected results. On checking, the Pins RST and GND get shorted sometimes. And sometimes even VCC, RST and GND get shorted. I also checked the small reset switch on board, and it is working fine.
I contacted Gravitech, but they aren't responding.
What can be the issue with my arduino Nano? I haven't used it yet in any of my project. Just the Blink program that I uploaded 3 years ago on it, was the last time I saw it working.
Any help would be greatly appreciated.

Have you verified that the RST pin isn't shorting to ground when uploading?  (After the reset button is released, of course).

Select Tools>Processor>ATmega328p(old bootloader)
I was having the same problem. The default uploaded sketch was causing the problem. The code was reading one of the analog pins and throwing the value via serial port and causing the problem. Changing to old bootloader fixed it for me

good morning. this is a question from 2016. new bootloader for Nano was introduced this year with the Old bootloader option in IDE

Ow i didnt know this. I faced this problem recently and found this fix working for me so i shared. Cheers

source: Stack Exchange

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

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

sort: votes


text:
Serial.println for pointers to the byte datatype behaves unexpectedly
byte subkeys[16][48/8];

for (size_t address = 0; address < 16*6; address++)
    Serial.println( (byte) *(subkeys + address) );

Why won't the compiler handle this? It tells me

cast from 'byte* {aka unsigned char*}' to 'byte {aka unsigned char}' loses precision [-fpermissive]

If I omit the (byte) part, it tells me

call of overloaded 'println(byte [6])' is ambiguous

I have no idea what's happening.

A byte is to small to store a pointer value. Instead to casting to
byte, you should cast to uintptr_t, which is guaranteed to be large
enough. On an AVR-based device like the Uno, this is the same as
uint16_t or unsigned int, but uintptr_t is more general.
Edit: From your comment it would seem you want to print the contents
of the array instead of the addresses of the rows. The obvious way is to
loop with two indices:
for (size_t i = 0; i < 16; i++) for (size_t j = 0; j < 6; j++)
    Serial.println(subkeys[i][j]);

If you really want to use subkeys as a 1D array, then cast it to a
byte *, which is the type a 1D array would naturally decay to:
for (size_t address = 0; address < 16*6; address++)
    Serial.println(((byte *) subkeys)[address]);

But *(subkeys + address) is not a pointer. It is a value in subkeys array. Am I wrong?

No, subkeys is an array of arrays of bytes, then *subkeys (as well as subkeys[address], which is a nicer syntax for *(subkeys + address)) is an array of 6 bytes. In most cases, arrays decay to pointers when you use them. You should probably start by telling us what you want to achieve.

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


text:
Send array of Infrared codes
I'm having a bit of a problem when sending IR Codes stored in variables. I swear I had this convered up already. I don't actually know the reason why I can't use variables in the first place. I receive data over Bluetooth Serial Com and I'm using an Arduino ProMicro as ISP for the Arduino Nano.
I want to send data over Serial comm and then send an IR code to the end receiver.
Here is some of the code():
#include <IRremote.h> // IR Library - Encode/Decode

void irSerial( char SerChar[] ) // Receive array of characters

char IDChar[]={'s', 'i', 'u'}; // List of Serial Char to identify position
String HRD[]={"Power", "Input", "ChaUp"}; // Action referece
byte CodesIR[]={0x61A0F00F, 0x61A048B7, 0x61A050AF}; // IR Codes
int IRArray = 2; // Size Of The array

if ( SerChar[0] == 's' ) { // Compare Array
  for (int CountIR = 0; CountIR <= IRArray; CountIR++){ // Loop through array
    if ( SerChar[0] == IDChar[CountIR]) {
       bluetooth.println(HRD[CountIR]); // Send String in array - Works
       SendIR.sendNEC(CodesIR[CountIR],32); // Send IR in array position
    }
  }
}
}

There's not a problem with the current expression as it compiles normally and I can send serial data normally finishing the function. If I replace the array CodesIR[CountIR] for example with 0x61A0F00F then it works perfectly.
How can I use a variable instead? Can anyone help? It is the byte CodesIR[] ??
I used a Switch/Case and it works but I prefer a variable/array and less useless coding. Thanks for understanding!

What are you trying to achieve? I don't know what library you're using, but it seems to me that you try to compare if SerChar[0..2] is equal to IDChar[0..2], and send the corresponding code for those that are equal. Maybe you could include a bit more code or an explanation

Well yes I'm comparing those values based on what I receive over serial. Everything works fine. The thing is that it seems I'm not using the correct data type for the IR codes. I'll rephrase my question! Thanks for your concern.

Well as usual it was something stupid (-__-) I changed the byte array for long and it worked perfectly.
Here is the complete code working():
#include <IRremote.h> // IR Library - Encode/Decode

void irSerial( char SerChar[] ) { // Receive array of characters

    char IDChar[]={'s', 'i', 'u'}; // List of Serial Char to identify position
    String HRD[]={"Power", "Input", "ChaUp"}; // Action reference
    long CodesIR[]={0x61A0F00F, 0x61A048B7, 0x61A050AF}; // IR Codes
    int IRArray = 3; // Size Of The array # Edit

    if ( SerChar[0] == 's' ) { // Compare Array
      for (int CountIR = 0; CountIR < IRArray; CountIR++){ // Loop through array # Edit
        if ( SerChar[0] == IDChar[CountIR]) {
           Serial.println(HRD[CountIR]); // Send String in array - Works
           SendIR.sendNEC(CodesIR[CountIR],32); // Send IR in array position
        }
      }
    }
}

Great job. P.S. To make your code a bit more intuitive, you could change IRArray = 2 to IRArray = 3, and then use CountIR < IRArray for the loop.

Thanks! I'll hope this could be of some help. I'll edit my response following your advice. Many thanks for pointing that out.


text:
Making MCUs Arduino Compatiable
I have recently just built a custom arduino using the schematics found on their website. As awesome as this little processor is, I need more power. I have been thinking of making my own MCU, but wanted to know if it is possible to make them compatible with the arduino software. It would be very nice to not have to rewrite my existing programs.
If so, how would I go about doing that? If this is not a possibility (or just not a good idea for any reason), which language should I learn to start programming these upper level MCUs.
If I do have to start using a different language, what kind of software do I use to upload the code to these processors? And do they have the common features like Serial Monitor and Serial Plotter like the Arduino IDE does.

There are several "Arduino compatible" boards with ARM core mcu, over at mbed.org (note: my employer makes one of them, the MAX32600MBED.)

What do you mean by "power"? Actual electrical power, i.e. "more watts" or more computational power, i.e. "more MIPS" (or "more MHz's")? It is not clear from your question.

There's already arduino compatible 32-bit microcontroller boards (ARM,MIPS,X86 ....) - see the wikipedia "List of Arduino boards and compatible systems"

You are speaking of porting. The arduino environment is built around a set of libraries and commands that are designed to abstract the low level access to a simpler high level language. In order to make arduino code work on a new microcontroller, you would have to rewrite and recreate the libraries using the low level access of your target microcontroller.
For example, Energia is a port of the Arduino libraries to the Texas Instruments MSP430 line of microcontrollers. Since not all features are the same, some code does not just drop in directly but additional code or libraries could be added to fix that. Even the Arduino IDE, the program used to write code and program the arduino was ported.
It would not be a trivial thing to port an entire library base.

As to your other questions, you would code your new microcontroller in any language it's programmer and compiler can use. Likely C or C++. Arduinos are typically programmed in C++. You should look into the manufacturer of your MCU to find out what software to use, and what libraries they offer. They likely do not offer something like the serial monitor right out of the box.

...but no porting is necessary, if one chooses a more potent MCU for which a port already exists.


text:
Only half of the 16x2 LCD appears
I searched for answers but I didn't found any answers to my problem. Actually, I use my Arduino with a 16x2 LCD screen. But as the title says, only the half of the screen displays (8x2), the other side just doesn't turn on. Do someone knows how to solve this problem?

In order to get good help in solving your problem, please provide more details on your specific situation. Include your wiring diagram (schematic, or something similar) and the code you are using, and as much information as you know about the LCD panel you have (datasheet, source, etc.)

Try configuring it as 8x4 I found many strange configurations when I bought cheap LCDs from China.

i've never seen/heard of that particular problem/failure mode, so it might be defective.

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


text:
How to stop and repeat a melody using a button?
How can we make our melody stop when we press the button the first time and repeat the melody when we press the button the second time?
// Noterna defineras

#define NOTE_B0  31
#define NOTE_C1  33
#define NOTE_CS1 35
#define NOTE_D1  37
#define NOTE_DS1 39
#define NOTE_E1  41
#define NOTE_F1  44
#define NOTE_FS1 46
#define NOTE_G1  49
#define NOTE_GS1 52
#define NOTE_A1  55
#define NOTE_AS1 58
#define NOTE_B1  62
#define NOTE_C2  65
#define NOTE_CS2 69
#define NOTE_D2  73
#define NOTE_DS2 78
#define NOTE_E2  82
#define NOTE_F2  87
#define NOTE_FS2 93
#define NOTE_G2  98
#define NOTE_GS2 104
#define NOTE_A2  110
#define NOTE_AS2 117
#define NOTE_B2  123
#define NOTE_C3  131
#define NOTE_CS3 139
#define NOTE_D3  147
#define NOTE_DS3 156
#define NOTE_E3  165
#define NOTE_F3  175
#define NOTE_FS3 185
#define NOTE_G3  196
#define NOTE_GS3 208
#define NOTE_A3  220
#define NOTE_AS3 233
#define NOTE_B3  247
#define NOTE_C4  262
#define NOTE_CS4 277
#define NOTE_D4  294
#define NOTE_DS4 311
#define NOTE_E4  330
#define NOTE_F4  349
#define NOTE_FS4 370
#define NOTE_G4  392
#define NOTE_GS4 415
#define NOTE_A4  440
#define NOTE_AS4 466
#define NOTE_B4  494
#define NOTE_C5  523
#define NOTE_CS5 554
#define NOTE_D5  587
#define NOTE_DS5 622
#define NOTE_E5  659
#define NOTE_F5  698
#define NOTE_FS5 740
#define NOTE_G5  784
#define NOTE_GS5 831
#define NOTE_A5  880
#define NOTE_AS5 932
#define NOTE_B5  988
#define NOTE_C6  1047
#define NOTE_CS6 1109
#define NOTE_D6  1175
#define NOTE_DS6 1245
#define NOTE_E6  1319
#define NOTE_F6  1397
#define NOTE_FS6 1480
#define NOTE_G6  1568
#define NOTE_GS6 1661
#define NOTE_A6  1760
#define NOTE_AS6 1865
#define NOTE_B6  1976
#define NOTE_C7  2093
#define NOTE_CS7 2217
#define NOTE_D7  2349
#define NOTE_DS7 2489
#define NOTE_E7  2637
#define NOTE_F7  2794
#define NOTE_FS7 2960
#define NOTE_G7  3136
#define NOTE_GS7 3322
#define NOTE_A7  3520
#define NOTE_AS7 3729
#define NOTE_B7  3951
#define NOTE_C8  4186
#define NOTE_CS8 4435
#define NOTE_D8  4699
#define NOTE_DS8 4978

#define melodyPin 3
//här är noterna som är i melodin
int melody[] = {
  NOTE_E7, NOTE_E7, 0, NOTE_E7,
  0, NOTE_C7, NOTE_E7, 0,
  NOTE_G7, 0, 0,  0,
  NOTE_G6, 0, 0, 0,

  NOTE_C7, 0, 0, NOTE_G6,
  0, 0, NOTE_E6, 0,
  0, NOTE_A6, 0, NOTE_B6,
  0, NOTE_AS6, NOTE_A6, 0,

  NOTE_G6, NOTE_E7, NOTE_G7,
  NOTE_A7, 0, NOTE_F7, NOTE_G7,
  0, NOTE_E7, 0, NOTE_C7,
  NOTE_D7, NOTE_B6, 0, 0,

  NOTE_C7, 0, 0, NOTE_G6,
  0, 0, NOTE_E6, 0,
  0, NOTE_A6, 0, NOTE_B6,
  0, NOTE_AS6, NOTE_A6, 0,

  NOTE_G6, NOTE_E7, NOTE_G7,
  NOTE_A7, 0, NOTE_F7, NOTE_G7,
  0, NOTE_E7, 0, NOTE_C7,
  NOTE_D7, NOTE_B6, 0, 0
};
//tempo mario(hastigheten på tonerna)
int tempo[] = {
  12, 12, 12, 12,
  12, 12, 12, 12,
  12, 12, 12, 12,
  12, 12, 12, 12,

  12, 12, 12, 12,
  12, 12, 12, 12,
  12, 12, 12, 12,
  12, 12, 12, 12,

  9, 9, 9,
  12, 12, 12, 12,
  12, 12, 12, 12,
  12, 12, 12, 12,

  12, 12, 12, 12,
  12, 12, 12, 12,
  12, 12, 12, 12,
  12, 12, 12, 12,

  9, 9, 9,
  12, 12, 12, 12,
  12, 12, 12, 12,
  12, 12, 12, 12,
};

// här bestämmer jag vilken pin sakerna ska sitta på
const int ledPin = 13;
const int buttonPin = 4;
const int buzzerPin = 3;
int musikSpelar = 0;
int buttonState = 0;
int musik = 1;
int notlangd = 0;

void setup(void)
{
  pinMode(buzzerPin, OUTPUT);//buzzer
  pinMode(buttonPin, INPUT); // knappen
  pinMode(ledPin, OUTPUT);// lampa på arduinon

}
void loop()
{

  buttonState = digitalRead(buttonPin);

  if(digitalRead(buttonPin)==0){
    delay(10);
  }
  if(digitalRead(buttonPin)==1){
    sing(musik); //Här spelar jag musiken
    musikSpelar = 1;
  }
  if(digitalRead(buttonPin)==0){
    delay(10);
  }
   if(musikSpelar == 1){
    //buzzer(melodyPin, 0, notlangd);
    musikSpelar = 0;
  }
}

void sing(int musik) {
  // upprepning av noterna i melodi:

    Serial.println(" 'Mario Theme'");
    int size = sizeof(melody) / sizeof(int);
    for (int Noten = 0; Noten < size; Noten++) {

      // för att räkna ut längden på noterna, tar man en sekund och dividerar på nottypen

      //vilket resuletar i att fjärde noten = 1000 / 4, åttonde noten = 1000/8, etc.

      notlangd = 1000 / tempo[Noten];

      buzzer(melodyPin, melody[Noten], notlangd);

      // för att hålla isär noterna, sätter jag ett minimum på tiden mellan dom.
      // notens längd + 30% ( va de som fungerade bäst:)
      int pausMellanTon = notlangd * 1.30;
      delay(pausMellanTon);

      // sluta spela tonerna:
      //buzzer(melodyPin, 0, notlangd);
    }

}

void buzzer(int targetPin, long frekvens, long length) {
  digitalWrite(13, HIGH);
  long delayValue = 1000000 / frekvens / 2;

  // räknar ut pausen mellan varje byte
  //// 1 sek i microsekunder, delat på frekvensen , sedan delat på hälften

  long numCycles = frekvens * length / 1000;

  // Beräkna antalet cykler för korrekt timing
  //// multiplisera frekvensen ,vilket egentligen är kretslopp per sekund, med antalet sekunder till
  //// det totala antalet "kretslopp"

  for (long i = 0; i < numCycles; i++) { // för den uträknade tiden...

    digitalWrite(targetPin, HIGH); // buzzern är på high för att den ska låta

    delayMicroseconds(delayValue); // vänta på den uträknade pausen

    digitalWrite(targetPin, LOW); // ha buzzern på pin low...

    delayMicroseconds(delayValue); // wait again or the calculated delay value
  }
  digitalWrite(13, LOW);

}

You need to explain your code, what it does, and the section you need help with. (Having comments in Swedish doesn't help most of your readers.)

https://www.arduino.cc/en/Tutorial/InputPullupSerial


text:
Setup Firmata for PC-less usage
I want to use an Arduino Uno with Firmata as a standalone datalogger for recording analog signals. I will use power banks to power the Arduino. How is it possible to setup Firmata pins once with PC and use that battery powered in PC-less situation?

how do you want to use Firmata without computer? Arduino with Firmata is a slave that can do nothing without commands from master


text:
what is welding plate?
I was looking at arduino nano boards here. Description says the arduino board is without welding plate. What does it mean for the user? If I buy this product will there be any issue? I understand that this board does not come with two headers soldered and I am OK with that.


text:
rev id and read_rev_id() function
What is a rev id? I have looked everywhere for a proper definition but I haven't found anything. I am trying to understand the code below. I don't understand why this read_rev_id function is necessary and yes, I tried to look in the user manual for the IMU I am using but it is practically none-existent. I am using the myAHRS IMU and the only manual I could find, on GitHub, didn't even show a register by this name.
void setup()
{
  //Initialization
  Wire.begin();
  Serial.begin(115200);
  who_am_i();
  read_rev_id();
  delay(1000); //Wait for 1second.
}

somebody named one of their functions read_rev_id.  ... look to where you got the program.

You haven't provided enough information for anyone to easily help you. Assuming that you took your code from GitHub myAHRS_plus_i2c.ino you can look further down the file to find the definition of read_rev_id(). It simply reads the revision number from the AHRS chip and displays it on the console. Since this is all that it does you could leave out the call to read_rev_id(). But if you are going to use it then be aware that it contains an obvious bug. The second read() should be to I2C_SLAVE_REG_REV_ID_MINOR.
//READ REVISION ID
int read_rev_id()
{
    uint8_t id_1 = 0;
    uint8_t id_2 = 0;
    read(I2C_SLAVE_REG_REV_ID_MAJOR, &id_1, 1);
    read(I2C_SLAVE_REG_REV_ID_MAJOR, &id_2, 1);
    Serial.print("READ REVISION ID= "); Serial.print(id_1); Serial.println(id_2);
}


text:
NodeMCU with RFID RC522 and I2C interface LCD module together

I'm newbie in Arduino programming so I hope to get a clear answer.
I have NodeMCU v1 12-E, I connected it with RFID RC522 as in attachment picture.
Now my question:
I need to connect I2C interface LCD module with it to print some words in.
The RFID use the default SDA and SCL pins on NodeMCU V1.0 "D1 and D2" also when I see wiring for the LCD I2C it use same D1 and D2 pins.
So now if I change the RFID instance creation code to
MFRC522 mfrc522(0,2);

//SS_PIN 3 RST_PIN 4

Is the RFID will work as previous pins and the LCD will work also?

this is will not work in I2C bus just go with the UART protocol this will work perfectly and its communication is very easy

You can have multiple devices on the I2C bus so long as they all have different addresses.  This means you should be able to connect D1 and D2 to the RFID and LCD.  HOWEVER I'm not sure that you are using I2C to talk to the RFID board, if you aren't then you may need to move the RFID boards pins and leave I2C on D1&2.

Thank you for reply Code Gorilla, I tried to change i2c to d3 and d4 for RFID, and the default d1 and d2 for I2C lcd module. they worked perfectly together.


text:
I want to play a sound based on my ultrason sensor reading
The idea is to play the tone that is given by the center value read it by the center ultrasound sensor.
The code that is in Arduino is this one:
#include NewPing.h

#define PING_CENTER  2  // Arduino pin tied to both trigger and echo pins on the ultrasonic sensor.
#define PING_RIGHT  3
#define PING_LEFT  4
#define PING_MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
#define buzzerPin = 10

long buzzerFreq1; // The frequency to buzz the buzzer
unsigned int BUZZ_FREQ_MAX = 2500; // Maximum frequency for the buzzer
unsigned int US_MAX = 2023; // Maximum value for ultrason sensor
int c1;

NewPing sonar2(PING_CENTER, PING_CENTER, PING_MAX_DISTANCE); // NewPing setup of pin and maximum distance.
NewPing sonar3(PING_RIGHT, PING_RIGHT, PING_MAX_DISTANCE);
NewPing sonar4(PING_LEFT, PING_LEFT, PING_MAX_DISTANCE);

void setup() {
  Serial.begin(9600);
  pinMode(buzzerPin, OUTPUT); // set pin for buzzer output
}

void loop() {
  buzzerFreq1 = (center * BUZZ_FREQ_MAX) / US_MAX;
  buzz(buzzerPin,buzzerFreq1,10);
  // tone(buzzerPin, center);
  delay(500);  // Wait 500ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
  unsigned int center = sonar2.ping() / US_ROUNDTRIP_CM; // Send ping, get ping time in microseconds (uS) and convert it to centimeters (cm)
  unsigned int right = sonar3.ping() / US_ROUNDTRIP_CM;
  unsigned int left = sonar4.ping() / US_ROUNDTRIP_CM;
  // Serial.println("Distance: " + String(distanceInCms) + "cm");

  Serial.println(center);
  Serial.println(right);
  Serial.println(left);

}

 // buzz(buzzerPin, buzzerFreq1, 10);
 void buzz(int targetPin, long frequency, long length) {
 // int c1 = center;
  buzzerFreq1 = (center * BUZZ_FREQ_MAX) / US_MAX;
  long delayValue = 1000000/frequency/2;

  int numCycles = frequency * length/1000;

  for (int i=0; i < numCycles; i++){
    digitalWrite(targetPin,HIGH);
    delayMicroseconds(delayValue);
    digitalWrite(targetPin,LOW);
    delayMicroseconds(delayValue);
  }
}

And I receive the following error that I have no idea how to solve it.
ultrason_onewire_sound.cpp: In function ‘void setup()’:
ultrason_onewire_sound.cpp:26:11: error: expected primary-expression before ‘=’ token
ultrason_onewire_sound.cpp: In function ‘void loop()’:
ultrason_onewire_sound.cpp:38:8: error: expected primary-expression before ‘=’ token
ultrason_onewire_sound.cpp: In function ‘void buzz(int, long int, long int)’:
ultrason_onewire_sound.cpp:48:18: error: ‘center’ was not declared in this scope

#define buzzerPin = 10 shouldn't have an = in it.
With the = pinMode(buzzerPin, OUTPUT); will turn into pinMode(= 10, OUTPUT); by the pre-processor. Which would give the error, complaining about an = token, you got.

You should use arduino built in tone command to play sounds with a buzzer, it will simplify your code and your errors.


text:
I want to move the mouse pointer with an Arduino and ultrasonic sensor
I want to move the mouse pointer with an Arduino and ultrasonic sensor but when I compiled it says

Mouse.h not found

and I don't know what I can do.
Here is my code;
 #include <Mouse.h>

int echoPinCursor=2;
int trigPinCursor=3;

int echoPinBtn=4;
int trigPinBtn=5;
int echoPinScroll=6;
int trigPinScroll=7;
int x;
int y;
long duracionCursor, distanciaCursor;
void setup() {
 Serial.begin(9600);
 pinMode(trigPinCursor, OUTPUT);
 pinMode(echoPinCursor, INPUT);
 pinMode(trigPinBtn, OUTPUT);
 pinMode(echoPinBtn, INPUT);
 pinMode(trigPinScroll, OUTPUT);
 pinMode(echoPinScroll, INPUT);

}

void loop() {

    //mover el cursor
  int direccionx=moverx();
  int direcciony=movery();

  Mouse.move(direccionx, direcciony,0);
  delay(2);

}

int moverx(){
      distanciaCursor=obtener_distanciaCursor();
  if (distanciaCursor >= 1  || distanciaCursor <= 11){
       x--;
     }
   if (distanciaCursor >= 12 || distanciaCursor <= 24){
       x++;
      }
     return x;
}

int movery(){
      distanciaCursor=obtener_distanciaCursor();
     if (distanciaCursor >= 25 || distanciaCursor <= 37){
       y--;
       }
   if (distanciaCursor >= 38 || distanciaCursor <= 50){
       y++;
      }
  return y;
}

long obtener_distanciaCursor(void)
{
  digitalWrite(trigPinCursor, LOW);
 delayMicroseconds(2);

 digitalWrite(trigPinCursor, HIGH);
 delayMicroseconds(10);

 digitalWrite(trigPinCursor, LOW);
 duracionCursor = pulseIn(echoPinCursor, HIGH);

 distanciaCursor = duracionCursor/58.2;
return(distanciaCursor);

}

That's because the Uno can't be a mouse.  For that you need the Leonardo or something else with a similar "U" style microcontroller.
If you are adventurous, and you have a genuine Arduino, you can reprogram the USB controller chip with new firmware so it thinks it's a mouse, but programming the main MCU is then a real chore.


text:
Seeking to measure back EMF of an electric motor via Arduino
Is it possible to measure the back EMF of a motor, using just the Arduino and no sensors?
Or what type of sensor do I need? One that measures current?

There is no need to measure the windings of the motor... please see the great write up for full details using an Arduino to sense the back EMF on a PWM driven motor to control the speed. This can be applied to a 3 phase motor as well, see Back EMF.
This person uses the analog input and a voltage divider to sense when the EMF happened, basically he gets the motor running, then periodically grounds one side of the motor through the H-Bridge he is using to drive it, and the other side of the  motor goes to a voltage divider into the Arduino... and it is also an open circuit at this time so the voltage generated is from the collapsing of the coil field so if it is 12V it becomes a safe 4V at the Arduino Analog input.
Now your question says "measure the back EMF", what I provided senses the back EMF... to measure it you just need to sample the Analog pin a bunch of times, and that will give you a reference of the max amplitude.

You will need at least an external current sensor, the arduino has no way of measuring current built in. You will also need to measure the winding resistance of the motor beforehand. look to this answer for a good explanation:
https://electronics.stackexchange.com/questions/54997/how-can-i-measure-back-emf-to-infer-the-speed-of-a-dc-motor
DC current sensors compatible with arduino should not be hard to find; just search one of the standard hobby electronics components sites.

Technically EMF is a voltage, not a current.

Take a look at this website:
http://www.vwlowen.co.uk/arduino/current/current.html
It shows how to make a create a simple current sensor with just a few resistors.

Links to external resources are encouraged, but please add context around the link so your fellow users will have some idea what it is and why it’s there. Always quote the most relevant part of an important link, in case the target site is unreachable or goes permanently offline.

EMF is a voltage, not a current.


text:
millis() function always returns same value
I'm trying to program an Arduino MKR1000 and I am using the millis() function to emulate a traditional timer.  The problem is that any call to millis() inside the debounceTimer() function returns the same value.  I only added the Serial.print to debug.
I left out a decent bit of the code to simplify your reading of it.  It works by waiting for an interrupt on pin 4 which then calls the runTimers() function and that calls the debounceTimer() function and within that the millis() function is called. The debouncetimer() function keeps getting called until the 10 ms has elapsed and then should end the timer.  The problem is that the millis() function stops returning a value that goes up.
#define doorIntPin 4
unsigned char sysEnabled = 0;
unsigned long debounceTimerPlace =0;
unsigned char debounceTimerOn =0;

void setup() {
  Serial.begin(9600);
  attachInterrupt(doorIntPin, doorOpens, LOW);
  interrupts();
}

void loop() {

}
void runTimers(){
  Serial.print('r');
  while(alarmTimerOn || debounceTimerOn || enablingTimerOn){
     if(alarmTimerOn)
      alarmTimer();
    if(enablingTimerOn)
      enablingTimer();
    if(debounceTimerOn)
      debounceTimer();
  }
}

void debounceTimer(){
  unsigned long time = millis()- debounceTimerPlace;
  Serial.println(millis() & 0xFFFF, DEC);
  if(sysEnabled && time> 10){
    debounceTimerOn=0;
  }
}
void doorOpens() {
  Serial.print('o');
  if(!debounceTimerOn){
      debounceTimerPlace = millis();
      debounceTimerOn=1;
  }
  runTimers();
}

I suspect that in the background an interrupt is being called than increments the value millis() returns and somehow my external interrupt is disabling that.  I don't know why this is happening or how to fix it.
Any ideas?

You never exit the ISR, hence all interrupts are disabled. Do the minimum work possible within an ISR, and have the main loop outside.

Thanks.  The thing is I'm trying to get the mkr1000 to sleep when not in use.  I've tried to execute the wait for interrupt function but i dont see how to.  Do you know how i could do this in the Arduino IDE?

To answer your question about millis(), it uses interrupts to function, and so you can't call it within an ISR.  According to this: https://www.arduino.cc/en/Reference/AttachInterrupt, you should be able to use delayMicrosconds() within an ISR, since it (reportedly) doesn't use interrupts.

The problem is that the millis() function stops returning a value that goes up.

That's right. The value returned by millis() is incremented by an ISR which won't be called inside your other ISR.
You can use micros() which will increment. However that will only be good up to approximately 1 ms. The main rule of ISRs is that you don't attempt to do delays inside them.


text:
HC-SR04 distance measuring without delay?
I am using the HC-SR04 ultra sound sensor for Arduino. I have used the following code to calculate distance and it works perfectly.
  long duration;
  digitalWrite(trigger, LOW);
  delayMicroseconds(2);
  digitalWrite(trigger, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigger, LOW);
  duration = pulseIn(echo, HIGH);
  distance = (duration/2) / 29.1;

However I want to use three more of these sensors, for a total of four. This block of code will be called every time I want to find the distance of one of the sensors. I am worried however that delayMicroseconds() pauses the entire program and that I cannot perform other tasks in while the sensors are working (e.g. driving wheels, it's a robot). The following code is object oriented for each sensor.
class distSensor{
   int trigPin;
   int echoPin;
   int distance;

   //Will be used in timer
   unsigned long previousMillis;

   public:
   distSensor(int tPin,int ePin){
   trigPin = tPin;
   echoPin = ePin;

   pinMode(trigPin, OUTPUT);
   pinMode(echoPin, INPUT);

   previousMillis = 0;
 }

 int calculateDistance(){

  //records time since program start
  unsigned long currentMillis = millis();

  long duration;
  digitalWrite(trigPin, LOW);

  //check if the previous time the method was called is greater than the interval of 2
  if(currentMillis - previousMillis > 2){
    digitalWrite(trigPin, HIGH);
    previousMillis = currentMillis;
  }

  //check if distance between current time and previous time it was called is greater than interval of 10.
  if(currentMillis - previousMillis > 10){
      digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
  }
  return distance;
 }
};

In the calculateDistance() method I am trying to do the same thing as the first code but without delay() and instead a timer. But when I run the program it does not work and distance is read as 0. Can anyone help me rewrite the HC-SR04 code from the start that doesn't delay the whole program?

Trying to use multiple sound based distance sensors at the same time may be problematic.  If they should "hear" each other their operation my result in unexpected values.  Consider using optical distance sensors based on the parallax principle.

theyre faced perpendicular and in opposite directions, thats not the issue

Likely there are configurations (room corners) which may still confuse sodar and sonar sensors which are trying to sample at the same time.

pulseIn() also blocks, so that won't help; you need an interrupt.

You said that the distance read is 0 ; your code does not work because you trigger the sensor with delays of 2ms and 10ms, you should use delayMicroseconds of 2us and 10us. As these delays are in us, you dont need to avoid them, you can use delayMicroseconds in your codes. The pulseIn() function blocks for too long, this is the one you have to avoid with interrupt as dandavis said.

delay() causes the processor to do nothing but wait.  You need to switch to millis().
In your code, you need to "grab" the current time using millis() and store it in a variable.  Add the number of milliseconds that you want to wait to this variable - you will have to consider the case where this value will overflow for a complete solution. Then, in your code, you need to create an infinite loop where you check what millis() returns.  When your stored value and millis() match, it is time to execute the code that would normally come after the delay() call.
Here, Arduino Playground - How and Why to avoid delay(), delay() and millis() are discussed in detail.
So that this answer will cover your question, consider placing all your events which need to be timed into this one infinite loop.  Also, consider keeping independent variables, one for each timed event, such that different events are timed independently.

` //check if the previous time the method was called is greater than the interval of 2
if(currentMillis - previousMillis > 2){
digitalWrite(trigPin, HIGH);
previousMillis = currentMillis;
}
//check if distance between current time and previous time it was called is greater than interval of 10.
if(currentMillis - previousMillis > 10){
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
} `
I have done that already but it still does not work. currentmillis is the time counted from program start,

That is a very difficult comment to read.   You need to consider overflow of the variable type used and of the type returned by the medthod call to millis().  I don't think you included that in your comment above.  Also, for the way you are describing events, you might also have to worry about using unsigned integers.  It may be simpler to check if millis() returns an expected value rather than finding the difference between what millis() returns and some variable.

enter code here
#define ECHO 5        // Pin received echo pulse
#define TRIGGER 6     // Pin sends shot pulse

int distance; // the distance in cms
unsigned long previousMicros = 0; // will sotre last time TRIGGER was updated
long OnTime = 10; //microseconds of on-time
long OffTime = 2; //microseconds of off-time
unsigned long previousMillis = 0; //will store last time viewTime was updated
int triggerState = LOW; // triggerState used to set it up
long duration;
void setup()
{
  Serial.begin(9600);
  pinMode(ECHO, INPUT);
  pinMode(TRIGGER, OUTPUT);
}

void loop()
{
  // check to see if it's time to change the state of the TRIGGER
  unsigned long currentMicros = micros();
  if((triggerState == LOW) && (currentMicros - previousMicros >= OffTime))
   {
     triggerState = HIGH; // turn it on
     previousMicros = currentMicros; // remember the time
     digitalWrite(TRIGGER, triggerState); // update the actual trigger
   }
   else if((triggerState == HIGH) && (currentMicros - previousMicros >= OnTime))
   {
     triggerState = LOW; // turn it off
     previousMicros = currentMicros; // remember the time
     digitalWrite(TRIGGER, triggerState); // update the actual trigger
   }

duration = pulseIn(ECHO,HIGH  );
Serial.println(distance);
distance = ((duration*0.034)/2);
Serial.print("distance: ");

}

this will run your code without delay but the problem is you will get a zero every time resulting from pulseIn() which from there on I dont know how to fix it yet

unsigned long currentMillis = micros();
digitalWrite(Trig, LOW);

if (currentMillis - previousMillis > 4) {
  digitalWrite(Trig, HIGH);
  previousMillis = currentMillis;
}

if (currentMillis - previousMillis > 12) {
  digitalWrite(Trig, LOW);
  previousMillis = currentMillis;
}

impulseTime = pulseIn(Echo, HIGH);
distance_sm = impulseTime / 58; // convert to centimeters
distance = distance_sm;


text:
Basic C++ programming, how to pass constructor argument into class?
I'm having some programming problems.
So here's what's happening:
In my .ino file, I have a tft variable which holds the connection to a LCD. I want to make a class which can either automatically access that tft class contained in the .ino, or pass it into the constructor when it's created; so basically:
// assuming this is the .ino:

TFT_ILI9163C tft = TFT_ILI9163C(cs, dc, rst);

MenuClass *menu = MenuClass();
menu->init("Example", tft); // this should work and "menu" should now have access to the "tft" variable

Here's my Menu.cpp:
// Menu class

#include "Menu.h"
#include <SPI.h>
#include <Adafruit_GFX.h>
#include <TFT_ILI9163C.h>

String menName = "Unnamed";

void MenuClass::init(const String name)
{
    menName = name;
}

String MenuClass::getName() {
    return menName;
}

void MenuClass::draw() {
    tft.setCursor(2, 2);
    tft.print(menName);
}

MenuClass Menu;

Which argument is tft supposed to be passed as?

Assuming you want to require every instance of MenuClass should be associated with a TFT_ILI9163C display object, you could use something like this:
// MenuClass.h

class TFT_ILI9163C; // declare a class name which is defined in TFT_ILI9163C.h

class MenuClass
{
  private:
    // read-only private member initialized by constructor
    // (the m_ prefix is commonly used to denote class member values)
    TFT_ILI9163C* m_tft;

  public:
    // constructor
    MenuClass(TFT_ILI9163C* pTft) : m_tft(pTft) {};

  private:
    // private storage for the Name property
    String m_Name;
  public:
    // read the Name property
    String getName() {
      return m_Name;
    };
  public:
    // write the Name property
    void setName(String value) {
      m_Name = value;
    };

  public:
    void draw() {
      // the m_tft member is a reference to the display class
      m_tft->setCursor(2, 2);
      m_tft->print(m_Name);
    };
}
MenuClass Menu;

Note that there is only one constructor, and it requires a pointer to the TFT_ILI9163C display. The body of the constructor : m_tft(pTft) {}; initializes the private member m_tft with the constructor argument pTft, so  MenuClass member functions invoke TFT functions as m_tft->fn(args);  Since there is no "void constructor" MenuClass(void), m_tft is effectively guaranteed to point to a valid TFT_ILI9163C instance.
Since it looks like you were using menName kind of like a class property, I rewrote that in the more commonly used m_propertyname style. Your MenuClass::init() was behaving like a name property setter; I'm not sure whether menu initialization requires anything else. This simple example has class MenuClass defined entirely inside the header file.
Usage is pretty similar to your example code, except now the MenuClass constructor requires a pointer to a previously constructed TFT_ILI9163C display instance:
// Main application
#include <TFT_ILI9163C.h>
#include "MenuClass.h"
// ... etc ...

// the TFT_ILI9163C display instance
TFT_ILI9163C tft = TFT_ILI9163C(cs, dc, rst);

// an example menu that draws on the display
MenuClass *menuFoo = new MenuClass(&tft); // use new to get pointer to new class instance
// MenuClass *menuFoo = MenuClass(&tft); // cannot convert 'MenuClass' to 'MenuClass*' in initialization

void setup() {
  // an example menu that draws on the display
  menuFoo->setName("Example");
  menuFoo->draw();
}

If you wanted to pass the constructor an initial Name property value as well as the tft display pointer, you could define the constructor as
  public:
    // constructor
    MenuClass(TFT_ILI9163C* pTft, String name) : m_tft(pTft), m_Name(name) {};

You could even go a step further, and give the name argument a default value:
  public:
    // constructor
    MenuClass(TFT_ILI9163C* pTft, String name = "Unnamed") : m_tft(pTft), m_Name(name) {};

So with this modification, the expression MenuClass(&myTFT) is the same as the expression MenuClass(&myTFT, "Unnamed"), but you can still override the default value like MenuClass(&myTFT, "DoSomething").
It is also perfectly legal to put statements inside the { } block of the constructor, but in this example all of the work is accomplished by the :memberName(value) constructor syntax.
Edit: MenuClass *menuFoo = new MenuClass(&tft); thanks @BrettAM

MenuClass *menuFoo = MenuClass(&tft); looks fishy to me, does that actually compile? It looks like you mean MenuClass menuFoo(&tft); or MenuClass *menuFoo = new MenuClass(&tft);


text:
Attempt to change an ESP8266's flashs layout over-the-air
Backstory
Several Tasmota devices based on an ESP8285 have to be flashed with alien firmware. The devices' programming ports are not accessible (except for one dummy device which was cracked open for testing).
The Tasmota firmware currently installed is based on the Arduino core, uses ESP8266httpUpdate.h and allows to OTA-update from a http server.
Problem
The problem is that the Tasmota firmware for the ESP8266 (=8285) family always uses a 1MB partition scheme while my specific device is based on the ESP8285H16 which incorporates 2MB of flash.
The second half of flash memory is therefore unused.
What I want to do
Using only over-the-air updates I want to update the Tasmota devices' flash layout so that the full 2MB of flash can be used and eventually upload a firmware that is bigger than what's currently possible.
Ideally the final flash layout uses a completely new partition scheme.
How can it be achieved?
I know this can be challenging and will probably require multiple intermediate firmware versions.
This is okay because the upgrade process will not happen "in the field" (but still no physical access to the chips) and occasional fails are acceptable - the process will be tested beforehand.
There's already a related answer from @Majenko here, but it covers the ESP32.
While I know where to start with an ESP32, I'm a bit puzzled with the ESP8266/8285:
I tried to read the whole flash images of the device to get a picture of what I'm dealing with and found the flash layout to be completely different from what I'm used to (ESP32).
Mainly, there wasn't a partition table at flash address 0x8000 while the Espressif documention specifies this exact address.
I found almost no documentation about the ESP8266 partition scheme as defined by the Arduino core:

Where in flash is the partition table?
If there is none, how does OTA work on ESP8266?
Where in flash is the bootloader?
Where does the filesystem begin (if there is one)?

Requirements

The flash layout needs to be changed using only OTA updates
Any information stored in the current flash or filesystem may be deleted
Multi-step updates are no problem
There's physical access to one device so the routine can be tested

Edit: Illustration
This is the normal OTA routine according to the docs:

and this is what I have in mind:

But for this I need to know the borders of each section, ideally during runtime.

As it turns out the update routine of ESPhttpUpdate.h works just fine when the flash layout changes after an OTA update.
At least in my case where the second half of flash memory is unused.
If there was a file system in the initial installation, it will be lost.
Though, it should be possible to even preserve the filesystem if it is copied to the right location before a firmware with different partition scheme is uploaded, but I have no need to follow that path now...
to summarize...

A Tasmota firmware was installed on a 2MB ESP8285H16. Since Tasmota firmware for ESP8266/8285 devices uses only 1MB of flash - maybe something like ~500kB sketch, ~400kB OTA, ~100kB FS).
The second half of flash was unused and the maximum size of a firmware that could be directly uploaded over-the-air was therefore ~400kB .

An intermediate firmware was provided on a http server for the device to update.
This firmware:

was built for a 2MB flash layout (1MB sketch, ~700kB OTA, ~256kB FS)
contains nothing but Wifi login and the OTA routine
Upon success, this update will leave the flash in the new layout

With the additional 300kB of OTA memory, the device could now be updated to the final firmware. This firmware was built with the same partitioning like the intermediate firmware.

This is the platformio.ini which was used in my case:
[env:esp8285]
platform = espressif8266
framework = arduino
board = esp8285

board_build.filesystem = littlefs
board_build.ldscript = eagle.flash.2m256.ld
board_build.mcu=esp8285
board_upload.flash_size=2MB
board_build.flash_mode=dout

monitor_speed = 115200
upload_port = COM5

If there is only little space left for OTA in the original flash layout, the firmware binary can be gzip'ed to save some memory.


text:
Reading TCD1304 linear CCD Sensor
I want to read the TCD1304 linear CCD sensor with an ESP32 and I'm facing some problems. As a first "warm-up" and to get familiar with this sensor I tried to generate the sensors input signals using a timer interrupt and bitbanging, but soon I found out that the resulting signals were way to slow and I didn't get any useful readings.
The signals involved are:

SH (shift gate): determines the integration time
ICG (integration clear gate): used to transfer pixel values to the shift register
ΦM: (master clock): self-explanatory
OS: output signal

The timing of those signals seems to be quite critical (see diagram below) and need to be quite fast - supported master clock frequency ist 0.8-4MHz and an analog measurement has to be done after every 4th clock pulse (0.2-1MHz).

Right now I'm pretty lost and I believe that this task requires some progamming techniques that I'm not familiar with so far.
Basically, my question is:
What is the best way to generate those signals and how do I read the ADC at that high sampling rate/accurate in timing?
I have some ideas, but - as I said - I probably lack the required skills, so it's hard for me to decide which approach I should take:

Using a single timer and direct port manipulation:
This would be easy to implement, but my assumption is that the interrupts will fire much too frequently to handle the ISR (which would be more or less complex, even if I refactorize my current test code). Especially reading the ADC will take too much time, I guess.

using the ESP's I2S-ADC:
I have no experience with I2S. From what I understand it is good for reading the ADC with a high frequency, but it is typically used for periodic sampling. In my case I would need the readings to be aligned with the control signals and I don't know if that is possible/convenient with I2S-ADC.

using ADC-DMA:
@esben Rossel has a done great work providing a framwork for STM32s and the TCD1304 in which he uses DMA for readout. I have never used direct memory access, but I feel this is a promising approach. Unfortunately, the documentation of the ADC only covers the ADC-RTC mode while there is no information about how to use the ADC-DMA mode. If DMA is the way to go I appreciate any hints on how I can get started with DMA programming on the ESP32.

In the latter cases 2) and 3) I would still need to generate the driving pulses in a "CPU-friendly" manner, probably hardware PWM (?), while the analog reading has to be triggered at every fourth clock pulse.
Would I use one timer for each signal and if yes, how would I ensure that the signals have the correct phase offset? Also, how can I trigger the analog measurement after every 4th clock pulse?

I am not familiar with the internals of the ESP32, but if I were doing it on an equivalent PIC32 I'd probably use SPI to generate the clock signal, which I then divide by 2. SPI then generates an interrupt every 8 clocks (or 4 after dividing by 2) which triggers DMA to read from the ADC. Another DMA channel sends out dummy bytes through SPI to keep the clock running and performing enough transactions.   I2S relies on an external CODEC chip to do the ADC (and DAC).

@Majenko using SPI for clock generation is a nice idea, I like it! The ESP32's SPI supports 4-bit transmission mode, which seems to be perfect for this. But I still have no idea how I could synchronize the SPI dummy signal with the SH/ICG signals and how I would generate those. Do you think, bitbanging using a timer followed by a call to my dummy SPI transmission (which triggers ADC-DMA) could work?

The SPI interrupt could be used to manage those pulses I would think. You could also use it to start / stop the ADC reading DMA channel.

@Majenko concerning I2S: do you mean I2S actually requires external hardware? From what I understand, the ESP32's I2S interface is capable of reading the internal ADC to achieve sampling rates of up to ~300kHz, or am I wrong?

As I mentioned earlier, I am not familiar with the internals. They may have added some loopback to an internal CODEC I guess, but I haven't a clue. I've only ever worked with external CODEC chips. You'd have to consult the TRM datasheet.

By way of preface, the chip has been driven from a few different Arduino class boards.  It is not trivial, but with care it can be done and produce a usable result if you have (a) a fast enough analog input and (b) manage the electrical issues and timing correctly.
I posted a github repo on this at the following link.  The README has a detailed discussion with circuit analysis and examples and the repo has spice models, and cad files and code.
https://github.com/drmcnelson/Linear-CCD-with-LTSpice-KiCAD-Firmware-and-Python-Library
Now, for the question, is MCU xyz feasible for this?
I think it boils down to the following questions, which you might find answered in its documentation or can answer with a little bit of code and an oscilloscope.
(a) Can the MCU produce a clock on a digital pin at at least 800KSPS (the minimum master clock for the TCD1304)?
(b) Can it read the analog input at at least 200KSPS?
(c) What is needed to drive the analog input at that rate?  (Check series resistance and capacitance for the analog input).
(d) What is the overhead in time for reading and writing a digital pin?
(e) How much current is available on the digital i/o pins?  And how much current is needed for the SH and ICG pins to reach the required voltages in much less than 1 microsecond?
(f) Is the processor fast enough to be able to control the timing between assertions of the two digital pins and the analog input based on the master clock output from (a)?
If all of that works out, then you might have hope that it might work.    Now, you are going to have to try it.
As you may know, the commonly employed technique is to generate the master clock on a pin, tie it to a second pin and then loop over digital read on that second pin and fire off the sh, icg and analog read as appropriate.   You can try that, insert processor loops as needed for timing and use a scope to check it.
If you are stuck, post your code and scope traces and we can try to help you.

The question was specifically about driving/reading the chip with the given hardware (ESP32). Also, signal quality was fine from an electronical POV, just the timing/sync of the generated and captured signals was problematic and I didn't solve it since.
Thanks for the answer anyways, though it sounds a bit like crafted by ChatGPT :D


text:
Cannot understand why this code work but this not
I've done a simple aurduino sketch, I have this code, and this don't work:
#define voltageInput A0
int qntR;
float mr;
float qr;
float Distanza;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(voltageInput,INPUT);
  mr=(130-20)/float(1023-205);
  qr=20-mr*205;
  Serial.print(mr,4);
}

void loop() {
  // put your main code here, to run repeatedly:
  qntR=analogRead(voltageInput);
  Distanza=mr*qntR+qr;
  Serial.print("Distanza: ");
  Serial.print(Distanza);
  Serial.print(" cm");
  Serial.println("");
}

And the I have this code:
#define voltageInput A0
int qntR;
float mr;
float qr;
float Distanza;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(voltageInput,INPUT);
  mr=(130-20)/(1023-205);
  qr=20-mr*205;
  Serial.print(mr,4);
}

void loop() {
  // put your main code here, to run repeatedly:
  qntR=analogRead(voltageInput);
  Distanza=mr*qntR+qr;
  Serial.print("Distanza: ");
  Serial.print(Distanza);
  Serial.print(" cm");
  Serial.println("");
}

In which I have delete the float from mr=(130-20)/float(1023-205);,and if I delete the float the code stop working (mr is always equal to 0), why?

What is is that doesn't work? Please include the serial output

it say that mr is always equal to 0

Your problem is that you are doing integer maths.
mr = (130-20)/(1023-205)

reduces to:
mr = 110/818

Which normally equates to:
mr = 0.135

But since all those numbers are integers the result is an integer, and is truncated at the decimal point, which means that mr is assigned:
mr = 0

You can force floating point maths by either including a decimal point in one of the numbers, or adding the suffux f:
mr = (130-20)/(1023-205.0)

or
mr = (130-20)/(1023-205f)

Or casting a portion of the sum to a float as your other code does.

but why, I have previusly said that mr is a float variable

Because you have just numbers the preprocessor does the calculation, not the compiler. The compiler just gets the number 0.

so if I do math with integers, the preprocessor will truncate the number in an integer?

If you just have literal numbers, yes.

The expression (130-20)/(1023-205) contains only integers so it is evaluated in integer arithmetic, and converted to float only to make the assignment to mr possible. In this case, the compiler evaluated it since the constants are all  known at compile time, but it would get the same result if some of the elements were integer variables and had to be evaluated at run-time.

@Majenko  thanks a lot!

@JRobert thanks a lot!


text:
Switching from one color to another
I'm using ws2812b 2x2 LEDs and have it switching between green and red, but only one of my LEDs on my 2x2 is lighting up.
I'm using the "blink" FastLED sketch with Data pin 3 on my Arduino Uno, define led 4.
void loop() {
 // Turn the LED on, then pause
 leds[0] = CRGB::Red;
 FastLED.show();
 delay(5000);
 // Now turn the LED off, then pause
 leds[0] = CRGB::Green;
 FastLED.show();
 delay(5000);
}

Sorry i'm a Total Rookie, my question is how come only 1 of my 4 led's is blinking, did i miss something in the code.

your code blinks only one led ... have a close look at your code ... see if you can figure out how to light a different led ... also have a look at the example code in the arduino IDE

For changing the led color or making any other led to glow you have to put the led number instead of leds[led number]  in this case so your code will basically look like.
void loop() {
 // Turn the LED on, then pause
 leds[0] = CRGB::Red;
 leds[1] = CRGB::Red;
 leds[2] = CRGB::Red;
 leds[3] = CRGB::Red;
 FastLED.show();
 delay(5000);
 // Now turn the LED off, then pause
 leds[0] = CRGB::Green;
 leds[1] = CRGB::Green;
 leds[2] = CRGB::Green;
 leds[3] = CRGB::Green;
 FastLED.show();
 delay(5000);
}

Hope this helps

Thanks Guys, i assumed that my #define NUM_LEDS 4 would have made all 4 work but it is doing what i want it to now, thanks alot you guys

This is an addition to the answer of xbox gamer (which I upvoted), to prevent much duplicated code.
For loop
First we see, the 4 LEDs are made red or green (using green in the following case):
leds[0] = CRGB::Green;
leds[1] = CRGB::Green;
leds[2] = CRGB::Green;
leds[3] = CRGB::Green;

For this a for loop can be used counting from 0 to (excluding) 4:
for (led = 0; led < 4; led++)
{
    leds[led] = CRGB::Green;
}

Variant 1: Color argument
Next we see the first and last lines are almost identical. For this we can make a function, and change the variable items (like the color) with a variable passed to that function, which is called an argument:
First we create the loop function:
void loop()
{
   turnLEDs(CRGB::Red);   // Turn LEDs on (i.e. red), then pause
   turnLEDs(CRGB::Green); // Turn LEDs off (i.e. green), then pause
}

Then we need to make just a single function to change the color (place this before the loop function. The type of the color is enum HTMLColorCode, see http://fastled.io/docs/3.1/struct_c_r_g_b.html.
void turnLEDs(enum HTMLColorCode color)
{
    for (led = 0; led < 4; led++)
    {
        leds[led] = color;
    }
    FastLED.show();
    delay(5000);
}

Variant 2: Boolean argument
Another way, is to not pass the color, but pass ON or OFF, which is a boolean.
For this we can use the so-called ternary operator: a ? b : c which means: if a is true, use b, otherwise c. We get:
void turnLEDs(bool enable)
{
    for (led = 0; led < 4; led++)
    {
        leds[led] = enable ? CRGB::Red : CRGB::Green;
    }
    FastLED.show();
    delay(5000);
}

void loop()
{
   turnLEDs(true);
   turnLEDs(false);
}


text:
Strange values on Serial Monitor even with matched baud rate

I am using the Adafruit Flora, connected with a Max 4466 microphone sensor. When I read values from the pin numbered 12 (which is marked as a11 for analog input on the schematic of the flora) I get random characters in the serial monitor as shown in the attached image, with my code. Trying to read other pins that are connected to nothing doesn't read any information. My baud rate in the serial monitor and the code are the same as you can see in the image.
Looking at the max 4466 explanation on the Adafruit website it says you don't need a capacitor or anything and can just directly plug the out pin on the MAX 4466 to the analog pin on an Arduino. I'm not sure if a different protocol has to be followed for a Flora instead of an Arduino. It also says to convert the information to an actual signal I need to use the FFT libraries, but I don't think this input being read is even correct.
If the FFT library is the problem here, I would need help on how to use it because there is no clear value being read in the example code. I had to set up a delay in the code otherwise the IDE would crash from all the info.Additionally, the VCC on the max is connected to 3.3V, the GND to GND, and the OUT to the #12 pin on the Flora.

Try to print "Hello World" and nothing else. Tell us the result.

You can't concatenate string and value inside Serial.println().
Print them using two different Serial.println().
int pin12;
int A12 = A12;

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

void loop() {
  // put your main code here, to run repeatedly:
  pin12 = analogRead(A11);

  Serial.print("pin 12 is ");
  Serial.println(pin12);

  delay(5000);
}


text:
Connecting STM32F103C through USB as well as external power supply
What will happen if I connect a STM32F103C board to a USB as well as an external power supply? Will it work? Does the STM32 decide which power source to consider?

At least I know, you never should connect USB and the SWD VCC pin simultaneously. Do you have a datasheet/picture of your model? Since I cannot recall any STM32F103 board with external power supply (except normal supply via USB or SWD).

I don't have a picture of the model. With arduino boards you can have external and USB supply simultaneously. I'm using stm board now, so I just wanted to make sure if it's possible or not before I end up doing somthing I'll regret later on.

Without a link/datasheet I don't think anyone can answer. A picture is the least important, a link (on internet) or datasheet would help more. Arduino boards normally have an external power supplies, STM32 boards don't (unless shown otherwise).

you can test to see if there's a diode between the usb's 5 volt line and the devkit's 5V pin. If there is, you should be fine. If not, it will probably smoke something.


text:
I cannot compile the Arduino sketch when I remove the void loop function?
#include <AFMotor.h>

AF_DCMotor motor(2,MOTOR12_64KHZ);

void movefor ();

void moveback();

    void setup()

    {

    Serial.begin(9600);

    Serial.println("Motor test!");` `motor.setSpeed(200);

    movefor ();
    moveback ();
    }

        void movefor( ){
        motor.run(FORWARD);
    delay(1000);
    motor.run(RELEASE);
     delay(100);
    }

    void moveback( ) {
      motor.run(BACKWARD);
    delay(1000);
    motor.run(RELEASE);
     delay(100);
    }

While trying to compile this the error message is error compiling for board Arduino Uno
I want the functions outside loop so removed it.
Even if I keep void loop and leave it blank then my motors will like run forward, backward and forward afterwards continuously .

you get an linker error because the main function in core main.c calls the loop() function. it must exist.

Error is " cannot compile for the board Arduino Uno"

turn on verbose mode in Preferences

You can't, and shouldn't, remove the loop function. Arduino sketches must have a setup function and a loop function. The setup function is called once and the loop function is called repeatedly.
Just make your loop function look like this:
void loop() {
    movefor ();
    moveback ();
}

Your motor will move forward, then move backwards, forever.
Note that you should read up on how to avoid using the delay function. You really need to use millis() to do your timing rather than delays. Do an internet search on "Arduino blink no delay." That's basic Arduino programming.

There must be something wrong within the motor, circuit or the motor class.
What happens is when you use a setup and loop is the following:
setup();
while (1) { loop(); }

So the loop function is executed forever, if it is empty, nothing will happen. If you say that the motor runs forward, it is probably because of a wrong implementation of the motor class.
Arduino IDE dictates there is always a loop, and having an empty loop is the same as having no loop at all.
What you can try is:

In the setup, only execute movefor() and check what happens
Than only execute moveback() and check what happens
Than make combinations and see if the problem is inside movefor or moveback

For the first steps you can add a delay to easier see if there is a side effect.

I have tried what you said and code is working good  . I want forward motion then backward.   After this I want the same to be continuously moving forward and backward. But the problem that occurs is that it will always move forward after 1 forward and backward motion.  I think the loop is being continuously called and that is disturbing that's why I want to remove the loop. Maybe the  problem is in header file but how can I check this file?

you should get what you want when adding in setup: while(1) { movefor(); moveback(); } but I doubt that will work either. The header file can be found where you installed the library, you always can do a file search on your PC (crude way but it works; I don't know by head where the libraries are stored).

I have the AFMotor library in Documents-Arduino-libraries-AFMotor , everything looks fine here


text:
Servo Motors PWM pins, Arduino Uno
I wanted to understand how people are connecting a servo motor to pins without PWM, so I went searching and I read that the Servo library uses the timer1 of pin 9 and pin 10 to be able to use other pins.
I would like to ask some questions about this.

Could I connect a servo motor on pin 12 by emulation of the library, and another servo on pin 9, another on pin 10 and another on pin 11 at the same time?
Or using the Servo library the PWM in pin 9 and 10 stops working?
I could then through library emulation connect one servo on pin 7, another on 8, another on 12 and another on 13 ?
4 emulations at the same time?

How are you planning to emulate this? Afaik the servo lib uses hardware pwm but one can still use the timer interrupts to toggle any pin. This way, the resulting pwm is still triggered by hardware and therefore is still much more accurate than a pure soft pwm. The pwm on the oc pins can still be used then...

The library only uses the timer1 interrupt part, not the timer1-pwm part.

Have you read the Servo library page?
The library support upto 12 servos outputs. You can use any pin you want.
The library disables analogWrite() (PWM) functionality on pins 9 and 10.

For those looking for more information on PWM in arduino, a must see page is this one:
http://www.righto.com/2009/07/secrets-of-arduino-pwm.html. Once you read it you may undestand, what is software and hardware PWM and which are the limitations.
To do the software PWM the servo library takes over one of the three arduino's timers. So pin 9,10 are not available to analoWrite() anymore, resting Timer0 (pins 5,6) and Timer2 (pins 11,3).
Note that internally arduino must use Timer0 to its timing functions (such as delay(), milis(), etc).
So to answer your question:
1) Yes, you can since the library is managing your timers it may allocate fine (as software emulation though).
2) Yes and No. It works for the library itself but may be not at disposal for other libraries or for your code. Example: if you want use it along with RH_ASK (radio frequency library) you have an conflict of timer usage and may be needed to change the config of one of them to move to another Timer.
3) Yes.
4) Yes (you can get all 20 pins working as PWM if you want. SoftPWM library does that).
Best regards,
gl


text:
Why I cannot change array values even if a statement is successfully called? TFT Touch Screen
#include <Adafruit_GFX.h>    // Core graphics library
#include "LGDP4535.h" // Hardware-specific library
#include <zTouchScreen.h>
#define BOXSIZE   40
// Assign human-readable names to some common 16-bit color values:
#define BLACK   0x0000
#define BLUE    0x001F
#define RED     0xF800
#define GREEN   0x07E0
#define CYAN    0x07FF
#define MAGENTA 0xF81F
#define YELLOW  0xFFE0
#define WHITE   0xFFFF

LGDP4535 tft; // Using the shield, all control and data lines are fixed

#define YP A3  // must be an analog pin, use "An" notation!
#define XM A2  // must be an analog pin, use "An" notation!
#define YM 9   // can be a digital pin
#define XP 8   // can be a digital pin

// You need to calibrate to fit your LCD
#define TS_MINX 930
#define TS_MINY 903
#define TS_MAXX 142
#define TS_MAXY 117

#define PENRADIUS 3
#define MINPRESSURE 10
#define MAXPRESSURE 1000

int matrix[2][3]; // Initial Declaration
int array[3]

TouchScreen ts = TouchScreen(XP, YP, XM, YM, 300);

// array = start with 1 but the variable read start with 0
String ButtonAction[9]={"a", "b", "c", "d", "e", "f", "g", "h", "i"};
boolean ActiveMenu=true;

void setup(void) {
   Serial.begin(9600);
   tft.reset();
   tft.begin();
   ts.InitVariable(3, 240, 320, TS_MINX, TS_MAXX, TS_MINY, TS_MAXY, MINPRESSURE, MAXPRESSURE);
   tft.fillScreen(BLACK);
   DrawIt(CYAN, "draw");
   DrawIt(BLACK, "text");
}

void loop() {//SOME OTHER STUFF}

unsigned long DrawIt(uint16_t color, String CurrentAction) {

  int timedcycle=0;

  if (CurrentAction == "text") {
     int matrix[2][3]={{25,150,265},{45,100,155}};
     int array[3]={3,3,3};

     tft.setRotation(3);
     tft.setTextColor(BLACK);
     tft.setTextSize(1);

     Serial.println("Text Columns");
  }

  else if (CurrentAction == "draw") {
    int matrix[2][3]={{260,140,20},{40,150,95}};
    int array[3]={3,3,3};
  }

  Serial.println(CurrentAction);

  for(int j=0; j<3; j++) {
     for(int i=0; i<array[j]; i++) {

       if (CurrentAction == "draw") {

         if (timedcycle == 7) {
           tft.fillCircle(100, 160, 15, WHITE);
         }
         else {
           tft.fillRect(matrix[1][j], matrix[0][i], 20,40, color);
         }

       }
       else if (CurrentAction == "text") {
         if (timedcycle == 4) {
           true;
           //tft.fillCircle(100, 160, 15, WHITE);
         }
         else {
           tft.setCursor(matrix[0][j], matrix[1][i]);
           tft.println(ButtonAction[timedcycle]);
         }

       }
     timedcycle++;
     }
  }
}

So as you can see I'm trying to draw some things in a TFT Touch Screen. Everything seems to be working but no matter what I do I can't change the array value.
If I initialize the array variable with a predetermined value it won't change even if the statement is called correctly. I can see that it runs over serial but the array still doesn't change.
I suppose there's something wrong but I can't pinpoint what it is! Thanks in advance!

You have defined three matrix/array; one in the global context and one per block in the local context in DrawIt. The definitions in the local context are removed by the compiler as they are not used (drop out of context). What you need to do is assign the global matrix/array instead.

So my mistake is involved with variable declaration as my values are discarded by natural behaviour of the compiler. I didn't think of that but it's the same on other languages as well but I didn't took the "loop" and "setup" functions into account. Thanks for the quick explanation

It's because you are defining a new array every time, not modifying the existing one.
int matrix[2][3]={{25,150,265},{45,100,155}};

That line doesn't assign new values to the existing matrix array, instead it creates a new array called matrix which only exists within the current scope - that is, within the {...} defined by the if that it is within.
Instead you either need to assign values directly to the existing matrix array on a slice-by-slice basis (you cannot use {...} to assign them in bulk):
matrix[0][0] = 25;
matrix[0][1] = 150;
... etc ...

Alternatively, since the values are static, you can pre-define the different matrices in the global scope and then switch between them.  This can be done with the right kind of pointer. For instance:
int textMatrix[2][3] = {{260,140,20},{40,150,95}};
int (*matrix)[3];

void whateverTheFunctionIs() {
    if (whatever...) {
        matrix = textMatrix;
    }
}

In that example matrix is a pointer to an array of pointers, which is basically what a 2D array is internally.  It starts off by not being assigned to anything at all - it's just "dangling in the breeze".  When the if in your function is triggered the address that the matrix pointer points to is changed to that of the textMatrix 2D array, so any access to matrix[x][y] will be identical to accesses to textMatrix[x][y].

Can you provide an example on how can I accomplish that?

Instead if using int matrix... you just assign new values to the individual slices. Note that you cannot use the {...} notation for that but must assign each value individually. matrix[2][1] = 43

So the best option is to create another array with fixed values? Thanks for your answer and I'll check on this to accept your answer

I am at my desk now, so I can give a much fuller answer... check back in a mo for my edit.

I got an error with the global variable part: 182:13: error: cannot convert ‘int [2][3]’ to ‘int**’ in assignment. I'll try the first solution then

TBH I didn't actually try the code out - I may have made a mistake with it ;)

Appologies - the definition of matrix should have been: int (*matrix)[3];

Don't worry I'll rewrite my code again to include your edit for a later feedback. Thanks for your time and consideration


text:
How to choose a port on Arduino Create
I have connected my Mega2560 Arduino to my computer; locally everything works fine - I have been able to upload and run programs.
However, on Arduino Create, it shows that there's no connection to my board. I have downloaded the plugin. The instructions say to "choose a port", and in the image it displays a menu with "[board] at [port]" but in my menu there is no "at", it just says "Arduino/Genuino Mega or Mega 2560" with an option to choose a flavour, but no port.
How can I choose a port and get my Arduino connected?

Which operating system? I have used it, but it was slow and not pleasant to work with.

@Jot both Windows 10 and Mac OS Mojave. Both using Chrome


text:
Selection of External CT for my application
Here I have attached my ckt for my application. My application is Motor protection Relay. Based on Current sense of 3 CT tripping of relay will occur. Tripping might due to under/over/SC/Locked rotor Etc. Now I am facing in selection of CT and interfacing with Arduino Un0.
I know HP rating and its max current measurement range.

How to Select CT for my application based on Current measurement range
How Burden resistor calculated.
How Size of CT can be calculated.
How to judge max supply voltage supplied to Arduino
Type of CT to be used protection class CT or Normal CT
How to calculate Max Current level can read through CT. it will be mentioned in datasheet. what it will do when it cross rated current? means when it attain saturation if I use above circuit what is effect on Arduino Uno board.
How burden VA calculated here.

I have researched and got one of application where they using AC AC1030 datasheet
Ip=30A I max=75A
 turns ratio: 1000:1
 supply voltage = 220VAC
min power continuous CT can sense = 220X30 = 6.6 kW
Max power sense for short period=220*75=16.5 kW
 Irms=1.4*30A=42A

burden resistor= 2.5/(42/1000)=59.5ohm R1=R2=100kohm resistor.
Is it correct? What are other care I need to consider while taking hardware design?


text:
I am building an robotic arm by using flex sensor, servo and 2 xbees
Rx Code:
#include <Servo.h>
Servo myServo;

void setup() {
Serial.begin(9600);
myServo.attach(9);
delay(5000);
myServo.write(0);
}

void loop() {
  while(Serial.available()==0);

    int d = Serial.read() - '0';
    if(d>0)
    {
      int pos = map(d,0,9,0,180);
      pos = constrain(pos,0,180);
      myServo.write(pos);
      Serial.println(d);

      delay(50);
      }
      else
      {};

}

Tx code:
int sensorValue = 0;         // the sensor value
int sensorMin = 1023;        // minimum sensor value
int sensorMax = 0;           // maximum sensor value
int SensorMid = 0;
const int POWER_OF_TWO_TO_AVERAGE = 6;

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

  while (millis() < 10000) {
    digitalWrite(13,HIGH);
    sensorValue = analogRead(A1);
    if (sensorValue > sensorMax) {
      sensorMax = sensorValue;
    }
    if (sensorValue < sensorMin) {
      sensorMin = sensorValue;
    }
  }
  SensorMid = (sensorMin + sensorMax )/2;
  digitalWrite(13,LOW);
  }

void loop() {
int val = map(analogRead(A1),SensorMid,sensorMax,0,9);
Serial.println(val);
delay(100);
}

I am building a robotic arm and I am facing some problems regrading to the servos stability with the flex, I am using the flex as the transmitter and the servo as the receiver, and when I press my finger my servo doesn't move properly.
Any suggestions?

Please show your code (a minimal, complete example that demonstrates the problems), your wiring diagram or schematic, and a more detailed description of the "doesn't move properly" issue. Otherwise, all anyone can do is make uninformed guesses.

@josecanuc, Please refer to the question, since I have edited the question

what does this mean? i press my finger

I am using flex sensor, it gives the signals by bending your finger @jsotola

Have you tried taking a mean of for example 10 or 20 consecutive readings? All analog signals have noise on them, which you can reduce by taking the mean value

Without knowing more about the actual problem of "doesn't move properly", what I initially see is that you are transmitting values 0-9 by using Serial.println(), which sends the byte data, and also a newline (ASCII value 10), so your RX code is probably getting alternating input of the intended value, and the value 10, which is getting subtracted from 48 (the ASCII value of '0'), mapped and constrained to 0.
Try changing your TX script to call Serial.print() instead. Your receiver doesn't care about each value showing up on a new line -- it doesn't know about lines.

What I mean by it doesn't move properly, that when I try bending the flex sensor, I guess that the servo doesn't receive the data properly due to the flex sensor resolution.

I think that the servo is not stable because that the flex is keep sending values even when I’m not touching it, how can I solve this problem @jose can u c

Why do you think that? If you want help from the public here, you have to provide actual data.


text:
Serial communication between Arduino and Java NetBeans
I am new to this serial communication between Arduino and Java NetBeans.
I am doing some small project and I need to get data from external EEPROM 24LC256 which is connected to Arduino UNO and pass it to the Java NetBeans platform not the Eclipse. So far I am using RXTX driver to communicate with Arduino in Java and easily get the data from serial monitor of Arduino IDE.
So can anyone help me, on how can I serially communicate with this external EEPROM using Java?
import gnu.io.*;
import java.util.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.util.Enumeration;

public class last extends javax.swing.JFrame implements SerialPortEventListener  {
    SerialPort serialPort;
    private static final String PORT_NAMES[] = {
        "COM3", // Windows
    };
    private BufferedReader input;
    private OutputStream output;   /** The output stream to the port */
    private static final int TIME_OUT = 2000; /** Milliseconds to block while waiting for port open */
    private static final int DATA_RATE = 9600;  /** Default bits per second for COM port. */
    public void initialize() {
        CommPortIdentifier portId = null;
        Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

        while (portEnum.hasMoreElements()) {   //First, Find an instance of serial port as set in PORT_NAMES.
            CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
            for (String portName : PORT_NAMES) {
                if (currPortId.getName().equals(portName)) {
                    portId = currPortId;
                    break;
                }
            }
        }
        if (portId == null) {
            System.out.println("Could not find COM port.");
            return;
        }
        try {          // open serial port, and use class name for the appName.
            serialPort = (SerialPort) portId.open(this.getClass().getName(), TIME_OUT);
            serialPort.setSerialPortParams(DATA_RATE,  // set port parameters
                    SerialPort.DATABITS_8,
                    SerialPort.STOPBITS_1,
                    SerialPort.PARITY_NONE);

            input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));   // open the streams
            output = serialPort.getOutputStream();
            serialPort.addEventListener(this);   // add event listeners
            serialPort.notifyOnDataAvailable(true);
        } catch (Exception e) {
            System.err.println(e.toString());
        }}

    /**
     * This should be called when you stop using the port.
     * This will prevent port locking on platforms like Linux.
     */
    public synchronized void close() {
        if (serialPort != null) {
            serialPort.removeEventListener();
            serialPort.close();
        }}

    /**
     * Handle an event on the serial port. Read the data and print it.
     */
    public synchronized void serialEvent(SerialPortEvent oEvent) {
        if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
            try {
                String inputLine=input.readLine();
                System.out.println("the state of the led is  "+inputLine);
            } catch (Exception e) {
                System.err.println(e.toString());
            }
        }
        // Ignore all the other eventTypes, but you should consider the other ones.
    }

    public static void main(String[] args) throws Exception {
        last main = new last();
        main.initialize();
        Thread t = new Thread() {
            public void run() { //the following line will keep this app alive for 1000 seconds,
                //waiting for events to occur and responding to them (printing incoming messages to console).
                try {Thread.sleep(1000000);} catch (InterruptedException ie) {}
            }
        };
        t.start();
        System.out.println("Started");
    }
}

This is the code in Java NetBeans.

Perhaps you can attach your code for higher rate of getting a proper answer. Just a wild guess, have you try softserial?

here i wrote code

Your EEPROM has I2C interface, so first you shall program Arduino to access it: An I2C EEPROM Class for Arduino
Then implement some kind of communication protocol over serial, to send commands instructing Arduino to read/write from EEPROM. For example, with following commands:

for writing write:<address>,<count>,<data_as_hex_string>
for reading read:<address>,<count>
response for reading: <address>,<count>,<data_as_hex_string>

authors: นายช่าง จักร์กริช


text:
ESP-32 with tft display
I recently got a Adafruit TFT screen and an ESP-32 development kit. I was trying to interface these two the pin connections I used areas follows:
TFT   |   ESP-32
------+----------
3V3   |   Vcc
Gnd   |   Gnd
MOSI  |   GPIO19
SCK   |   GPIO18
CS    |   GPIO5
D/C   |   GPIO16
RST   |   GPIO 17

I used this library: https://github.com/MartyMacGyver/ESP32_Adafruit_ILI9341
The SPI library used was the one that comes while installing Arduino support for ESP-32.
The code compiles and uploads without any error/ warning but the TFT screen does not show any response (except powering up).
This is the code I used for testing:
//#include <Adafruit_ST7735.h>

#include<Adafruit_ILI9341.h>
#include <Adafruit_GFX.h>
#include "SPI.h"

#define TFT_CS     5
#define TFT_RST    17
#define TFT_DC     16

// Use hardware SPI (on Uno, #13, #12, #11) and the above for CS/DC
//Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC);
// If using the breakout, change pins as desired
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS ,TFT_DC, 23, 18, TFT_RST);

void setup() {
    // put your setup code here, to run once:
    Serial.begin(115200);
    Serial.println("In the setup.");
    //tft.initR(INITR_BLACKTAB);
    unsigned long t=micros();
    tft.fillScreen(ILI9341_RED);
    Serial.println(micros()-t);
}

void loop() {
    // put your main code here, to run repeatedly:

}

The code compiles and uploads without any error/warning but the TFT screen does not show any response (except powering up).
NOTE: The library works fine with Arduino Mega and TFT display.

MOSI and SCK both on GPIO19...?

I have now corrected the discription of connections sck is at pin 18 not 19.

Why have you commented out the TFT initialisation function?

That function works only wit h tft shield. I am using a separate breakout board so I have to innitialise in the format given two lines bellow.  : Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS ,TFT_DC, 23, 18, TFT_RST);

That instantiates the object, it doesn't initialise the TFT. I repeat: why have you commented out the initialisation function?

Also why tell the library MOSI is on 23 when it is on 19?

Ok, sorry for the delay, I had my exams. But I have finally solved the issue.
There were several issues:

MOSI should be connected to pin 23 not 19.
tft.begin() function should be in the setup to initialize the TFT. (for ILI9341)
The SPI library used should be the one that comes with ESP-32 support. The general SPI library for Arduino does not work with ESP-32.

Note: the ST7735 library currently does not work with ESP-32. It can be made to work by adding the following definitions given bellow to the Adafruit_ST7735.h header file.
    #elif defined(ESP32)
    volatile uint32_t *dataport, *clkport, *csport, *rsport;
    uint32_t  _cs, _rs, _rst, _sid, _sclk,
    datapinmask, clkpinmask, cspinmask, rspinmask,
    colstart, rowstart;

(add this just after the ESP8266 definitions).


text:
Testing ID and Serial Communication (Update)
Here is my challenge: I have to create a sketch where I would have a prompt asking the user to enter an ID. If it is successful, it would turn on the green LED and response with "Hello, your name is so-so."  If it failed, it would turn on the red LED and response with "Invalid username! Try again."
The code is here:
//Establish myID as CHAR data type
 char myID = 'tg123';
 //Establish testID to receive data to be tested against myID
 char testID;

 //Establish green and red LEDs to PWM pins
 const int gLED = 10;
 const int rLED = 5;

 void setup()
 {
  //Establishing baud rate at 9600
  Serial.begin(9600);
  pinMode(gLED, OUTPUT);
  pinMode(rLED, OUTPUT);
 }

 void loop()
 {
  //Act when there are data in the buffer
  while (Serial.available())
  {
    testID = Serial.read();
    //If data = myID, turn on green LED and acknowledge
    if (testID == myID)
    {
      digitalWrite(gLED, HIGH);
      digitalWrite(rLED, LOW);
      Serial.println("Hello! Your name is Trevor.");
      delay(5000);
    }
    else
    {
      digitalWrite(rLED, HIGH);
      digitalWrite(gLED, LOW);
      Serial.println("Invalid ID! Try again.");
      delay(2000);
    }
  }
 }

Two problems I have had with this:

The damn thing would print the line "Please enter your ID:" infinitely if it was inside the loop, so I got fed up and moved it to the set up, and
no matter what I enter in the serial monitor, it does not do anything.

Update: After reading Arduino's website, I found I can predefine the char data type by adding char myID = 'tg123';.  It is getting closer to achieving what I want, but it's exhibiting some strange behavior.  When I type in exactly tg123 in the serial monitor, it would report the error message as defined in the sketch before passing.

Your sketch assumes that the ID is a single character. If that is the case then comparing with 'tgreen123' will not work very well.

I have updated the original post.

You are assigning a string to a single character here.

char myID = 'tg123';

Instead you should make it a String variable. And compare it after all the characters are recieved.

String myID = "tg123";

And Here is the modified code you should test with. In this case I have assumed you simply write the ID (string) in serial terminal and hit enter.
N.B. If you want to enter each character one by one, then it will not be able to catch the whole string. For this case you have to add some time-out to wait for next character to arrive.
String recvData = "";
void loop()
{
  while (!Serial.available());
  while (Serial.available())
  {
    char ch = Serial.read();
    recvData += ch;
  }
  if (myID == recvData)
  {
    digitalWrite(gLED, HIGH);
    digitalWrite(rLED, LOW);
    Serial.println("Hello! Your name is Trevor.");
    delay(5000);
  }
  else
  {
    digitalWrite(rLED, HIGH);
    digitalWrite(gLED, LOW);
    Serial.println("Invalid ID! Try again.");
    delay(2000);
  }
  recvData = "";
 }

When you use the Arduino IDE to compile your code for an Uno, it will tell you

Sketch uses 2106 bytes (6%) of program storage space. Maximum is 32256 bytes.
  Global variables use 237 bytes (11%) of dynamic memory, leaving 1811 bytes for local variables. Maximum is 2048 bytes.

as if there had been a clean and correct compilation.  However, if you compile it via make and a makefile (see, eg, sudar's Arduino Makefile) you will see a warning like the following:

stringInit1.ino:2:14: warning: character constant too long for its type [enabled by default]
    char myID = 'tg123';

where stringInit1 stands for whatever you call your sketch.
The char data type stands for a single character.  To represent a text string, use either an array of characters (for example, char *myID = "tg123" or char myID[] = "tg123") or a String type (which, in general, is problematic on small-RAM embedded processors).
Then, to make the comparison, keep track of how many characters have been input so far, and as you input each character, compare it to the current character of myID, clearing a match-flag if characters don't match.  Eg, if (testChar != myID[currentCount]) matchFlag = false;.  Note, initialize currentCount to zero and matchFlag to true in setup() and before each retry.

I agree.  Serial.read() will only bring in a single character.  You do have the option of using Serial.readstring, but then you can't compare it to chars.  I like @James' idea of just checking with each character whether or not you have the whole ID.  Then you wouldn't even need to press enter when you have it right.  But you could type the entire constitution of the US, newlines and all, and the program would do nothing.  I also agree that you may have an uploading error because you say it prompts you for your ID but I don't see that in the code.  Might be an older version that is running.


text:
Attiny13 project with leds and electret microphone
I want to make a project similar to this Turn Signal Biking Jacket
.
But, instead of using Arduino Lilypad I want to use an 8 pin attiny13A-SH and want to use one electret microphone instead of the buttons.
I want to use led's only for the left, right and a stop indicator(on the back, i don't want the leds on the sides like the instructable project).
According to me, the leds require 1 pin each and will share a common gnd(that's 4 pins).
The microphone will require 1 additional pin, with 1 going to the gnd (5 pins).
And I might require 2 pins for the power outlet (6 pins out of 8).
Now, i am a newbie in all this stuff so i don't want to go about experimenting with the chips. I am ready to disable the reset pin cause i wont require the chip again. I have got a couple of instructable's to help me in the programming and set-up plan(though they have used Arduino Uno or Lilypad), so I only want to know if it is possible to make the project with the attiny13a chip without the requirement of any additional parts.
Also, as an alternative, i wanted to use these leds instead of the lilypad led's, so i want to know if i can do the model in exactly the same way without using any mofsets etc(i just want 6 leds on each side). I'm extremely sorry for my horrible drawing(First time and no correct tools. used paint!)
ANY HELP IS APPRECIATED.

want to use 1 electret microphone instead of the buttons.

In what way do you want to use the microphone? You do realise, don't you, that an Arduino can't understand speech (or much of anything really) without powerful extra hardware? A microphone by itself is pretty much useless, especially without any form of preamp and signal conditioning.

i only want to know if it is possible to make the project with the attiny13a chip without the requirement of any additional parts.

No, it's not possible. You will require lots more parts. You can't just take an arbitrary chip and connect it to a battery and expect it to work properly. You need to consider correct supply voltages (voltage regulation or boosting depending on your power source), decoupling capacitors, drive circuitry, amplification, signal processing, etc...

i wanted to use these leds instead of the lilypad led's, so i want to know if i can do the model in exactly the same way without using any mofsets etc

Again, no.  Those are 12V LED strips. You need both a 12V supply (and the associated regulation down to 5V to power the ATTiny etc) and MOSFETs (or something similar) to allow the ATTiny to switch that 12V to the LED strips as needed.

Thanks for your reply. But I didn't get your point on the microphone thing since there are loads of voice controlled leds tutorials on the net which use the same mic and the bitvoicer software

Are you going to carry your PC around with you on your bike?

A simple answer would be "No, it's not possible"
You cannot run a single chip independently without any protection and regulating components(e.g. capacitor, regulator, current limiting resistor)
Also by replacing components with other ones, it would require you additional adjustments in the code and also in the hardware(Referring to the replacing buttons with Electret Microphone). There is a reason for the Arduino Lilypad to have additional components so that it can run smoothly and avoid damages to both the user and the device itself.

There are many Tut's on making our own custom Arduino which uses a chip and a capacitor or something. Can I make it like that on a custom based pcb(the chip)

Yes, you could make that, providing that you will use the required necessary basic components. I see that the size matters to you so I would recommend you to try to look also into other Arduino compatible boards like this one here from Adafruit , the Gemma(which is at the size of a Quarter!) and Flora.


text:
Unable to upload the data on thingspeak using uno and esp8266
I am able to connect to thingspeak but now able to upload the data. here are my set of commands:
AT+CIPMUX=0
OK

AT+CIPSTART="TCP","184.106.153.149", 80
OK
Linked

AT+CIPSTATUS
STATUS:3
+CIPSTATUS:0,"TCP","184.106.153.149",80,0
OK

AT+CIPSEND=45
> GET /update?api_key=DXDPC4MLXMXFB5TT&field1=60

busy s...

SEND OK

OK

and after some time unlink
I am giving these commands using arudino serial monitor.
Please help, I have searched a many blogs, youtube videos.

I got it working. Yo!
#include <SoftwareSerial.h>
#include <stdlib.h>

// LED
int ledPin = 13;
// LM35 analog input
int lm35Pin = 0;
float my_value = 22;
// replace with your channel's thingspeak API key
String apiKey = "9PJEF1EP8ZMVY5JA";

// connect 10 to TX of Serial USB
// connect 11 to RX of serial USB
SoftwareSerial ser(10, 11); // RX, TX

// this runs once
void setup() {
  // initialize the digital pin as an output.
  pinMode(ledPin, OUTPUT);

  // enable debug serial
  Serial.begin(9600);
  // enable software serial
  ser.begin(9600);

  // reset ESP8266
  ser.println("AT+RST");
}

// the loop
void loop() {

  // blink LED on board
  digitalWrite(ledPin, HIGH);
  delay(200);
  digitalWrite(ledPin, LOW);

  // read the value from LM35.
  // read 10 values for averaging.

  // convert to temp:
  // temp value is in 0-1023 range
  // LM35 outputs 10mV/degree C. ie, 1 Volt => 100 degrees C
  // So Temp = (avg_val/1023)*5 Volts * 100 degrees/Volt
  my_value++;
  float temp = my_value;

  // convert to string
  char buf[16];
  String strTemp = dtostrf(temp, 4, 1, buf);

  Serial.println(strTemp);

  // TCP connection
  String cmd = "AT+CIPSTART=\"TCP\",\"";
  cmd += "184.106.153.149"; // api.thingspeak.com
  cmd += "\",80";
  ser.println(cmd);

  if(ser.find("Error")){
    Serial.println("AT+CIPSTART error");
    return;
  }

  // prepare GET string
  String getStr = "GET /update?api_key=";
  getStr += apiKey;
  getStr +="&field1=";
  getStr += String(strTemp);
  getStr +="&field2=";
  getStr += String(strTemp);
  getStr += "\r\n\r\n";

  // send data length
  cmd = "AT+CIPSEND=";
  cmd += String(getStr.length());
  ser.println(cmd);
  Serial.println(cmd);

  if(ser.find(">")){
    ser.print(getStr);
    Serial.println(getStr);
  }
  else{
    ser.println("AT+CIPCLOSE");
    // alert user
    Serial.println("AT+CIPCLOSE");
  }

  // thingspeak needs 15 sec delay between updates
  ser.println("AT+RST");
  delay(30000);
}

You have a malformed HTTP request. You only have half of the first line.
A valid HTTP request would look more like this:
GET /update?api_key=DXDPC4MLXMXFB5TT&field1=60 HTTP/1.1
Host: api.thingspeak.com
Content-length: 0
Connection: close
<blank line>

Just sending "GET : ain't gonna work. For a start, the server won't know what protocol you're speaking (HTTP/1.1), nor what website it's supposed to direct the request to (Host: api.thingspeak.com). Also, the final extra blank line is required to finish the request.

Comments are not for extended discussion; this conversation has been moved to chat.