text:
strange strings

#include "Keypad.h"

char Incoming_value = 0;
String password = "123456";
String input = "";
const byte ROWS = 4; //four rows
const byte COLS = 4; //three columns
char keys[ROWS][COLS] = {
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
};

byte rowPins[ROWS] = {2, 3, 4, 5}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {6,7,8,9}; //connect to the column pinouts of the keypad

Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

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

void loop()
{
  if (Serial.available() > 0)
  {
    Incoming_value = Serial.read();
    Serial.print(Incoming_value);
    Serial.print("enter value");
    if (Incoming_value == '1') {
      digitalWrite(13, HIGH);
      Serial.print("ON");
    }
    else if (Incoming_value == '0') {
      Serial.print("OFF");
      digitalWrite(13, LOW);
    }
  }
  // Read the pushed button
  char key = keypad.getKey();
  input = input + key;
  // just print the pressed key
  if (key) {
    Serial.println(key);
  }
  if(key == '*' ){
    Serial.println(input);
    if( input == password){
      digitalWrite(13, HIGH);
    }
  }
  if(key == '#'){
    digitalWrite(13, LOW);
    input = "";
  }

/*
  // this checkes if 4 is pressed, then do something. Here  we print the text but you can control something.
  if (key == '4') {
    Serial.println("Key 4 is pressed");
          digitalWrite(13, HIGH);
      Serial.print("ON");
  }
    if (key == '5') {
    Serial.println("Key 5 is pressed");
          digitalWrite(13, LOW);
      Serial.print("ON");
  }
  */
}

when print input variable i get strange text like

⸮⸮⸮⸮⸮⸮⸮;⸮⸮ߵ⸮⸮⸮⸮u⸮⸮⸮⸮⸮⸮?/}⸮⸮⸮⸮⸮⸮~⸮⸮⸮⸮⸮-d

what i can do ?

Probably you haven't added a delay towards the end of void loop()

As an example : download JohnsProject/ArduOS from Github and run the main sketch there after putting the line of code that invokes the registry to run the shell app. You'll see the same strange thing happening

Also, try adding the delay as I said in void loop() in you sketch and see if it works.

Have you confirmed that your IDE serial monitor baud rate setting is 9600 (which is what your code assumes it is)?

@lurker , is my answer okay ? (Perhaps I can add your point on the baud rate setting in the Serial Monitor, if you wish ;) )

First of all you have to make sure, that you select the same baudrate in the Serial Monitor, that you used in your sketch with Serial.begin(). This error is very common and garbage values is the symptom of this.
But your code also has problems. You have the input variable of type String, which should hold the user input for comparison with the password. Directly after getting the key, you are appending this key to the string. You are assuming here, that keypad.getKey() is waiting for the user to actually press a key and then return that. But this is not the case. keypad.getKey() will return NO_KEY, when the user currently isn't pressing a key. This is defined in the Keypad library as '\0' (the null character), which marks the end of a string. Your code runs very fast, so you are adding more and more null characters to your string. Your strings gets bigger and bigger, filling your RAM very fast.
How to solve this: You should only use the return value of keypad.getKey(), if a key was actually pressed. Put all the code after it in an if statement, checking for NO_KEY:
// Read the pushed button
char key = keypad.getKey();
if(key != NO_KEY){
    input = input + key;
    // just print the pressed key
    if (key) {
        Serial.println(key);
    }
    if(key == '*' ){
        Serial.println(input);
        if( input == password){
            digitalWrite(13, HIGH);
        }
    }
    if(key == '#'){
        digitalWrite(13, LOW);
        input = "";
    }
}

Nice answer ! You corrected the code I wasn't able to ! (+1)

PS: @lurker's suggestion in the comments - check the baud rate setting in your serial monitor as well.
EDIT: I admit that the code in the previous version of this answer was foolishly typed out by me due to lack of patience, so I'll make up for my mistake(not in code, but as a full answer).
First of all, I didn't understand what you wanted to do with the Incoming_value variable in your sketch, so I'm not gonna talk about it; I'd suggest adding a sufficiently small delay at the end of the code in the loop. This should provide the serial port some time to handle the incoming data and stop printing the confusing output (perhaps; just because delays make your microcontroller wait for a while to get things done elsewhere , especially where the reception of data is slow and thus avoid collisions)
Also note that I am not a CS student or an electronics geek, but I am speaking from my guesswork. Any correction is accepted.

Given that most often delays do more harm than good, what is the rationale for adding them here? I can see how they could help on a program that sends data to a very slow receiver, but this is not the case here. To make the code “run smoothly” is overly vague.

@EdgarBonet sorry for the late reply. Note that at the place where the system is made to receive the keypresses, adding a delay allows the person to type the password (As in the example) key by key -  and now that reminds me of how foolishly I have added the code in my answer. Thanks a lot !! :D


text:
Would someone provide an example of extracting data from a char array?

I have tried so many things now that I am just confused.
I am not understanding the way char arrays work.
I can't get the date and names extracted.  And when I use just strings, I jam up the memory.

Below was my last attempt, before asking the question.
while (f.available()) {
  String line = f.readStringUntil('\n');

  if (line.startsWith("04-23")) {
    currentDay = 1;
    int str_len = line.length() + 1;
    char char_array[str_len];
    line.toCharArray(char_array, str_len);
    Serial.println(char_array);                 // Everything works to here
    for (int j = 0; j < 2; j++) {
      b += char_array[j];
    }
    bMth = b.toInt (); // This should be an int of the birth month in this case: 04
  }
}

Var:
format: MM-DD-YYYY,Name  // this is inside the file
line = "04-23-2020,James"  // This is the output from - Serial.println(char_array);

What I am trying to do is

Extract the month/day so that I can compare it to today.
The year so I can calculate the age.
The name to display on OLED.
Everything else seems to work, but I can't get my head
wrapped around the char array access.

To do this in PowerShell I would do:
$line = "04-23-2020,James"

$dob = ($line.Split(","))[0]
$bMth = ($dob.Split("-"))[0] # This is not used in this example
$bDy = ($dob.Split("-"))[1]  # This is not used in this example
$bYr = ($dob.Split("-"))[2]

$age = $(get-date -UFormat %Y) - $bYr

Clear-Host
Write-Host (@'
Name: {0}
Age:  {1}

'@ -f $($line.Split(","))[1], $age)

In Python:
import datetime as dt

line = "04-23-2020,James"

dob = (line.split(',')[0])
bMth = (dob.split("-"))[0] # This is not used in this example
bDy = (dob.split("-"))[1]  # This is not used in this example
bYr = (dob.split("-"))[2]

age = int(dt.datetime.now().year) - int(bYr)

print('Name: ',(line.split(',')[1]))
print('Age: ', age)

Does this help? https://majenko.co.uk/blog/splitting-text-c

I recommend learning how to use the strtok() function. It is also described in Majenkos blog entry

When working with Arduino, cplusplus.com is your friend. Scroll down and look on the left side under (string.h). Lot's of great char functions there. Other useful functions such as iota() - cplusplus.com.
Here's one way to accomplish the parsing of the input data.
// Sketch uses 2064 bytes (6%) of program storage space.
// Global variables use 323 bytes (15%) of dynamic memory.
// Arduino IDE 1.8.9.
char line[] = "04-23-2020,James";
char Name[100];
unsigned int Month, Day, Year;

// Make an attempt to validate the input data.
byte Counter = 0;

void setup(){

  Serial.begin(9600);

  char * pch = strtok(line, "-,");

  while(pch != NULL){
    if(Counter == 0){Month = atoi(pch);}
    else if(Counter == 1){Day = atoi(pch);}
    else if(Counter == 2){Year = atoi(pch);}
    else if(Counter == 3){strcpy(Name, pch);}
    pch = strtok(NULL, "-,");
    Counter += 1;
  }

  // Print out the data.
  if(Counter == 4){
    Serial.println(Month);
    Serial.println(Day);
    Serial.println(Year);
    Serial.println(Name);
  }
  else{
    Serial.println("Error");
  }

}

void loop(){}

You could try sscanf if your data format is fixed, something like this:
char line[] = "04-23-2020,James";
int day, month, year;
char name[100];
if (sscanf(line, "%d-%d-%d,%s", &month, &day, &year, name) == 4)
{
    // Process the four items.
}

but the code for scanf takes 1.5kB flash memory

source: Stack Exchange

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

sort: votes


text:
Blynk, but continue program if Blynk connection fails
I'm having an issue with Blynk.begin(auth, ssid, pass);
The problem is, when it fails to connect to the wifi, the rest of the program does not continue.
I'm using a Wemos D1 and it is also controlling some relays based on a temperature sensor.
But when there was a power outage and power comes back on, the programs should continue whether the wifi is working or not, so that relays can still be controlled by the temperature sensor reading.
What happens now is if there is a wifi issue when Wemos D1 is starting up again, the program simply stops in the void setup() at Blynk.begin(auth, ssid, pass); and the rest of the program cannot be executed.
Anyone knows how to avoid this?
Kind regards,
Peter

This has been a weakness with Blynk right along. The connect functions block and nothing else can execute until they return. In addition, some of the transmit-data functions block if your internet connection goes down or is carrying too much traffic for Blynk's traffic to complete in a timely way (how long is 'timely'?). I don't know a way around it other than possibly to make your own watchdog timer (one that can have a much longer timeout than 8 sec), and code your system to run without Blynk if it was restarted because of Blynk.

@JRobert, thank you for your comment!
At first I thought perhaps just moving the Blynk code completely out of the void setup() into the main loop, at the very end, but even then I'll get stuck if wifi fails for some reason.
I'm sure I'm missing something - not being very well experienced with anything more than the basic Blynk. Hard to imagine this is not a major issue when it comes to programs that need to execute important tasks regardless whether wifi is working or not...

this may help https://gist.github.com/mercdev/f0fea967a82fb87e92a425c5f12580af#file-blynk_wemos_d1_r2-ino-L276

https://docs.blynk.cc/#blynk-firmware-configuration-blynkconfig and the ESP8266_Standalone_Manual_IP example for Blynk library

You can try my Blynk_WM or Blynk_Async_WM library with their Blynk.begin() functions are not blocking.

Check Why using this Blynk_WiFiManager with MultiWiFi-MultiBlynk features
Why using this Blynk_WiFiManager with MultiWiFi-MultiBlynk features
You can see that the system automatically detects and connects to the best or avaiable WiFi APs and/or Blynk Servers, whenever interruption happens. This feature is very useful for systems requiring high degree of reliability.
Moreover, this Blynk.begin() is not a blocking call, so you can use it for critical functions requiring in loop().
Anyway, this is better for projects using Blynk just for GUI (graphical user interface).
In operation, if WiFi or Blynk connection is lost, Blynk.run() will try reconnecting automatically. Therefore, Blynk.run() must be called in the loop() function. Don't use:
void loop()
{
  if (Blynk.connected())
     Blynk.run();

  ...
}

just
void loop()
{
  Blynk.run();
  ...
}

It's also beneficial to search in Blynk Forum for more information and examples

Khoi, stack exchange policy requires to disclose that these are your libraries

Thanks Juraj, already update.

Yes, Blynk_WiFiManager is great.
I have modified DHT11ESP8266.ino to suit my needs and works.

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


text:
MacOS BigSur Arduino IDE No Ports Shown
I'm trying to get the Arduino IDE (1.8.13) installed on MacOS BigSur 11.0.1 and am unable to compile and run an Arduino sketch. There are no ports available in 'Tool' menu; the port item is grayed out.  The error message states that the IDE "Could not initialize class sun.security.ssl.SSLContextImpl$DefaultSSLContext".  I have installed the following Java code:
java 16.0.1 2021-04-20
Java(TM) SE Runtime Environment (build 16.0.1+9-24)
Java HotSpot(TM) 64-Bit Server VM (build 16.0.1+9-24, mixed mode, sharing)

Any insight would be most appreciated.  Thanks in advance.

I don't have a Mac, so I'm not likely to be of much use on this, but it would be good to confirm that the device shows up in /dev or whatever is in the Mac control panel that lists USB devices.  If it doesn't, then the SSL error is unrelated (which would kind of make sense) or, at a minimum, not entirely determining the problem.

@timemage serial ports are listed in /dev.

Solved: I opened Android Studio and there was a security update for Java 8 (I think) so I accepted it and installed it.  Now I can magically see serial ports in the Arduino IDE.  I wish I understood what happened, but for now the problem appears to be solved.  Thank you for allowing me to post here.

Odd.  The way the IDE comes packaged, at least for Linux and Windows, it has its own JRE bundled in.

With all the gatekeeper features on a Mac, perhaps it blocked the Java code when I downloaded the Arduino IDE?  Macs used to come with Java pre-installed, but I've read that they no longer do that.  It is a new 64 bit machine and I have to give special permission just to run my own apps developed and compiled on my old 32 bit system.

If you get to the point of having a definitive answer, it may make sense to post it as an answer.


text:
Arduino , python , pyfirmata , standard firmata
Is there a way to change arduino analog reference to EXTERNAL IN PYTHON using pyfirmata or any other library ?
Necessary Links : https://www.arduino.cc/reference/en/language/functions/analog-io/analogreference/
My sensor has a 3.3 volt operating voltage , my arduino has a 5 volt operating voltage.
As such in arduino using C++ and arduino module the scaling can be done using analogReference(External) and providing reference voltage to analog read?
IS there any equivalent to this in python, pyfirmata ?

No, not as far as I know. The firmata protocol does not include a command to set the analog reference. However, you can of course modify the firmata firmware to your liking. In the simplest case, just add the appropriate command to the setup() function of the main .ino.

I have been using pyfirmata for the previous projects. Since pyfirmata doesnt include the necessary function , you suggest adding analogreference(External) to the firmata module that i would have to upload and run on arduino , would that make the analog reference voltage external when accessing with pyfirmata and python?

@Shahanhasan Yes. Firmata doesn't use analogReference() anywhere in the code, so when you add analogReference(EXTERNAL) to the startup code, it should change the behavior when accessing it from pyfirmata.


text:
Arduino Uno R3 HID with HC-06 BT module
Im trying to make a macro pad using Arduino Uno r3 and 4x4 matrix (cherry blue clone) . I know using a pro micro is better than uno cause there isn't HID compatibility in uno but since i already have one , i want to work with this . I have already tested the macro pad after compiling and flashing a keyboard.hex file . But wondering if i buy a bt module like HC-06 (which is about 3.2$ here ) would that be able to send inputs even aftar flashing ? I have like basics coding knowledge so i have no clue what flashing actually would do to the module so . Anyone know would making that macro pad BT compatible    be possible or not ?

It is unclear to me, where you flashed what, so I will describe some basics.
The Uno cannot act as a keyboard/HID device, since the microcontroller on it (the Atmega328p) doesn't have native USB capability. For connecting to USB the Uno has a USB-to-Serial chip on it (actually another microcontroller, the Atmega32u4 I think). So with the Uno you only have a serial connection, unless you hack the Atmega32u4 and program it with your own firmware (firmware is a term for software, that runs very near to the hardware, in this case directly on the microcontroller, in contrast to normal software running on an operating system on a computer; so in the middle between hard- and software, thus firmware).
Flashing is the same as programming a microcontroller. It has this name, because the program is saved in flash memory on the microcontroller (that is a specific type of memory technology; the same technology, that USB sticks use for storing your data). Flashing the HC-06 means programming it with a different firmware.
All bluetooth devices use the same base technology (thought to be clear, BLE is a different technology). The role of the device depends on the characteristic/profile, that it exposes to the host. There are profiles for HID, Serial, Audio, ... .
The HC-06 is a bluetooth slave device, which acts as a bluetooth-serial-bridge (like the Atmega32u4 acts as a USB-serial-bridge). But this is a software limitation. The HC-06 has standard bluetooth hardware, but the firmware on it just gives you the Serial profile (in fact a HC-06 is mostly the same like the master device HC-05, just different firmware and corresponding breakout boards can break out other pins). So by flashing (programming) it with a different firmware, you can get different profiles. If you find a firmware, that gives you HID functionality, you can flash that to the HC-06 and use it. Though this is a bit hacky I think (haven't done it myself), so it might be a bit too much for a beginner.
Bluetooth Slave/Master: The bluetooth protocol uses fixed roles for the two connected devices. One is the master and one is the slave. The master controls, if the communication is really happening. For example a bluetooth headset is a slave device. You cannot connect the bluetooth headset to your bluetooth keyboard, because both are slave devices. You always need one master and one slave. The HC-05 is basically the same module as the HC-06, but it's firmware enables it do be master or slave (configurable by you). So some devices support both modes, but still in any specific connection they can only have one of the modes (need to either master OR slave at any time).

Anyone know would making that macro pad BT compatible be possible or not ?

Possible, yes. But I suggest you invest in buying a ready to use bluetooth HID controller (immediately found this one from adafruit, though you might might cheaper versions). That will be way easier, than directly jumping into flashing a HC-06. Though that is still a possible path to go.
Another way to go would be to just use the serial functionality and write a small program for your PC, which reads from the Serial interface and issues key strokes according to the serial data. Then you don't need to reflash the HC-06.

Thank you chrisl for the valuable answer . I understand what you were saying .. somewhat . The thing is im from a third world country and there aren't any products from adafruit . Actually tinypico was a really good choice for my project but if i wanted to get one from AliExpress i would have to pay 20$+ on just shipping so the cost is too much .

You can search for other product than the one from Adafruit. That was just the first, that came up, when I quickly searched for it. If there are no better/cheaper modules available for you, you need to compromise. Either going the steep learning curve to learn reflashing the HC-06 or by writing the program for your PC, that handles serial input.

" I understand what you were saying .. somewhat" - Can you pinpoint, what you are not understanding completely? Then I can try to improve my answer in that direction.

I didn't understood master-slave relation in the BT module . Its because i haven't done any research in that matter . So instead of bothering you i just wanted to do some study on that matter :) again ,thank you very much for your answers , now i know what i need to look into

I added a short paragraph about this to the answer. For now I leave the rest for you to research :D If you think my answer is correct, then you can accept it. That marks the question as correctly answered.


text:
Weight scale with Arduino: calibration step
I'm not an expert about Arduino and I'm studying to create a project related to the bees remote monitoring.
I would like to monitor the internal humidity and temperature and the weight of the beehive boxes.
About the weight parameter my idea is to make a structure with 4 load cells.
I watched some video tutorials related to the creation of a weight scale with Arduino. I saw that it's necessary to calibrate the scale without any weight on the scale every time that Arduino will be started.
I'm not able to understand if there is a way to have this calibration in a different way: I mean,  I will place the beehives on my weight scales only one time and Is not possible to remove and put them back for each calibration step.
Is it really necessary or is there a way to have the calibration with the weight on the scales also?

Once the cells are calibrated w/ no weight those values can be stored and used. It's possible there might be some drift over time (not sure) but for this use case it shouldn't be a huge issue, assuming you're after an approximate hive weight. I'd also imagine you're more interested in weight differential than absolute weight, e.g., "am I having honey tonight" or "where have my bees gone?!"

Can you share the source of your remark: "...I saw that it's necessary to calibrate the scale without any weight on the scale every time that Arduino will be started.".

(Also see https://github.com/sparkfun/HX711-Load-Cell-Amplifier, the calibration program makes note of applications where there's a "constant" weight on the load cells between power cycles, although your weight won't be constant. IIRC temperature can also affect readings.)

Problem completely solved by SparkFun: https://github.com/sparkfun/Beehive_WiFi

It may be that in this application (beehive monitoring) it is not required to re-calibrate your load sensors before each use.  When a person is observing a scale to measure their own weight they will be sensitive to the scale reading zero before each use.  Even though being, say, a lb off is likely less than a 1% error when measuring their total body weight.  This site talks about load cell calibration and "recommends a yearly recalibration interval".  They also talk about temperature compensation.
As temperature and humidity will be monitored.  And nonlinear load sensor response to weight can be compensated in software, consider testing your setup under different conditions to determine what considerations need to be taken into account to provide the desired accuracy.

This image is from https://www.futek.com/load-cell-calibration-services

What I can find about calibrating load cells is that they are subject to "electrical influence, mechanical effects, instrumentation faults and
loose cables etc."
In the case of beehives, I'd add temperature, water, ice, snow, dirt & dust, and debris from the bees. The calibration suggestions I found were to calibrate "periodically", which suggests to me that the suggestion to calibrate at every startup assumes that the calibration will be lost at every power-down. That does not have to be the case - it can be store in a non-volatile memory such as EEPROM.
What I do think you'll need to do is calibrate each cells at 0%, 10%, ..., etc., of its full load, probably to 120% or 130% to allow for wind loading and asymmetric loading within the hive, and at a range of temperatures, make a set of force vs. cell output and temperature, from which to interpolate to get the 4 partial hive-weights.
They probably will need to recalibrated periodically, but for your application, a tare-value, measured at a reproducible hive condition, may be sufficient, if all you need is a differential weight.


text:
Arduino battery capacity selection based on the current measurements
I'm sorry for this stupid question...
I'm not an electronic/electric expert..
In order to select the battery capacity as well as the solar panel I'm measuring the Arduino current consumption.
So, I connected my multimeter (in line) (I rotated the selector on 200mA) and I'm able to see the values that are:

around 85mA for  few seconds (around 8seconds) when the system works;
around 0.38 mA during the remaining 52 seconds when the system is in sleep mode.
I'll enable my system around 8s for each 15minutes (basically 4 times for hour)

In order to have a general idea, I would like to use a site like this https://www.digikey.it/en/resources/conversion-calculators/conversion-calculator-battery-life
Now, It's not clear for me how can I use the retrieved values:
Do I calculate the current consuming in 1h?
The values that I obtained are related to the current consumed for a second?
What I have to punt into the field "Device Consumption" on the linked web-site?

You have two current values and the approximate time those currents run for.  From that you can calculate the average current.
If you have 8 seconds "on" and (15*60-8) 892 seconds "off" that gives you:
(85 * 8) + (0.38 * 892)
------------------------
         900

Which comes out as 1.13mA on average at any point in time (that's a simple ratio calculation - the times don't matter, only the ratio between them).
Over the course of 1 hour you will consume around 1.13mA on average, which is 1.13mAh.
To run for 24 hours you will need 1.1324 = 27.2mAh. To run for a week it's 27.27 = 190mAh.
The calculations, as you can see, once you have the average current are pretty simple.
Of course you need to "derate" the results since batteries never hold the stated amount - that is both a "theoretical maximum" under ideal conditions, which degrades over time (as you will know when your phone battery starts dying too soon), plus you never run a battery completely flat.  Personally I like to double the capacity to err on the safe side.
You also know that you need to charge the batteries with at least an average of 1.13mA from your solar cells. That means working out what ratio of the time will be available for actual charging (daylight with good sun brightness) and calculating how much current you will need to generate during that time to allow the system to run in the dark.

How you obtained 1.13mA?
((85 * 8) + (0.38 * 892))/900 = 38.42
Do I missed some others calculation?

@Safari 858 = 680. 0.38892 = 338.96. 680+338.96 = 1018.96. 1018.96/900=1.13217...

:D :D :D Yeah! Sorry... wrong copy and paste :s


text:
Arduino motor shield not compatible with nodemcu
Hi to all first of All my english is not good I brought Arduino motor shield  and n..d. E.p 8266 but the connect pin are not compatible how i will connect to node i want to make robo car

Hard to say. There are at least two issues: mapping the Arduino shield pins to the 8266, and whether or not the shield library would work as-is on the 8266. You might be better off with a generic motor driver board.

Please provide a link to the motor shield.


text:
Read from lux hangs in bright light
I am using VMEL6040 sensors and occasionally under bright light the read can hang, rather than using a wdt to recover I would like to ask some questions about the library.
as for debugging the sensors run stabley (several days at reads every 250 ms) in low light, but over 6k lux they can crash.
I am using wire.h here
in the header
TwoWire *_i2cPort;

the read value calls the ReadRegister function:
uint16_t SparkFun_Ambient_Light::_readRegister(uint8_t _reg)
{

  uint16_t _regValue;

  _i2cPort->beginTransmission(_address);
  _i2cPort->write(_reg); // Moves pointer to register.
  _i2cPort->endTransmission(false); // 'False' here sends a restart message so that bus is not released
  _i2cPort->requestFrom(_address, static_cast<uint8_t>(2)); // Two reads for 16 bit registers
  _regValue = _i2cPort->read(); // LSB
  _regValue |= uint16_t(_i2cPort->read()) << 8; //MSB
  return(_regValue);

}

is there a reason they are not checking the return of the _i2cPort->endTransmission(false);call? I am wondering if I should check that and not call the requestFrom if it does, i.e.:
uint16_t SparkFun_Ambient_Light::_readRegister(uint8_t _reg)
{

  uint16_t _regValue;

  _i2cPort->beginTransmission(_address);
  _i2cPort->write(_reg); // Moves pointer to register.
  if (_i2cPort->endTransmission(false) == 0) { // 'False' here sends a restart message so that bus is not released
      _i2cPort->requestFrom(_address, static_cast<uint8_t>(2)); // Two reads for 16 bit registers
      _regValue = _i2cPort->read(); // LSB
      _regValue |= uint16_t(_i2cPort->read()) << 8; //MSB
      return(_regValue);
  }
  else
      return 0;
}

Or could my error be from the static casting do int?

I thought a static_cast was just a compile time cast; I don’t see how casting 2 to a byte would cause an error if that’s what the call expects (which IIRC it is).

static_cast<uint8_t>(2) is not necessary, if you read Wire source, you will see multiple overload functions to handle the type casting. 2) to cast a uint8_t1 to a uint16_t, it is (uint16_t) _i2cPort->read(), not uint16_t(_i2cPort->read() . 3) shouldn't uint16_t _regValue; ` be declared at your Class level? your code now declared it as a local variable, and you are returning a local variable's value, which may no longer exist (out of scope) when the program return from the function.

@hcheung: Returning a local variable's address would be an error. Returning it's value is perfectly fine.

the full library im using can be found here:
https://github.com/sparkfun/SparkFun_Ambient_Light_Sensor_Arduino_Library

I think i just figured it out _i2cPort->read(); returns a -1 on error duh

so I think I got it, the problem was that on a fail wire.read() returns an int -1
when that gets converted to a unint16 its a big number then it gets left shifted and overflows
the solution was:
uint16_t SparkFun_Ambient_Light::_readRegisterLight(uint8_t _reg)
{
    int lsb;
    int msb;

    _i2cPort->beginTransmission(_address);
    _i2cPort->write(_reg); // Moves pointer to register.
    if (_i2cPort->endTransmission(false) == 0) { // 'False' here sends a restart message so that bus is not released

        unsigned long tstamp = millis();
        while ((_i2cPort->available() < 2) && ((millis() - tstamp) < 10));

        if ((_i2cPort->available() < 2)) {
            _i2cPort->requestFrom(_address, 2); // Two reads for 16 bit registers
            lsb = _i2cPort->read(); // LSB
            msb = _i2cPort->read(); //MSB

            if ((lsb >= 0) && (lsb <= 256) && (msb >= 0) && (msb <= 256)) {
                _regValue = lsb + msb * 256;
            }
        }

        return(_regValue);
    }
    else
        return _regValue;//last read
}

This contains some extra error handling I added, but will leave in such as:

timeout on waiting for a response
checking on properly closing the bus in end transmission
checking for errors from the read

I didn't do error handling as I would need to rewrite the whole library, and for my application repeating the last reading is sufficient.


text:
Serial.println won't format DEC
This is weirding me out. So I wrote to the EEPROM and I would like to read from the address and format it in Base 10, err... Decimal. The normal number thingy that's not ASCII. But it keeps returning ASCII values when I write:
Serial.println(EEPROM.read(address), DEC).
Wait for the weird part, when I format in other bases like, say BIN, or OCT, it outputs in the correct base. Please help. Here's the full snippet of the tiny program.
#include <EEPROM.h>
int addr = 0;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);

}

void loop() {
  // put your main code here, to run repeatedly:
  if(Serial.available() > 0){
    int rc = Serial.read();
    EEPROM.write(addr, rc);
    Serial.println(EEPROM.read(addr), DEC);
  }

}

you write into the EEPROM the received character, not a number. you print a number.

I do not understand what you are expecting your program to do.  Computers (usually) communicate using ASCII.  You read 1 value from another computer.  That's likely ASCII.  You store this into the EEPROM.  Then you print  that from the EEPROM back to another computer.  And you see what you initially typed in.  Sounds normal.  Wait, was your assignment to read ASCII, convert that into a number to store into the EEPROM then read that number out and print it?  If so, you are missing steps.  Sounds like you need to go back and 1st understand what the problem is trying to teach you.

The problem is that I write an integer into the EEPROM but it prints out ASCII even with the "DEC" argument. However, when I switch the "DEC" to BIN or OCT, it prints out Binary and Octal values respectively. But when I use "DEC" it only gives me the ASCII rather than the exact DEC value of the integer that I put in. Am I missing something?

What do you mean 'the integer I put in'? How are you putting in an integer over serial, which works on ASCII characters?

rewrite your code to print integers from 0 to 20 ... what do you see?

Please [edit] your question and show us what you get and what you expect. This means some example of input and output. And why you think it works for other bases.

I finally figured it out. Apparently, when I call Serial.read() and assign it to "int rc", It sort of converts the actual ASCII values into integer. So reading the number 3 from the Serial monitor and assigning it to rc stores 51 in rc. So the trick I found to that was to use
int rc = Serial.read()-'0'

That way, I am storing 51-48 which is, 3 (Since 48 is the ASCII value for 0).
Thanks.

Serial.read() returns a character, which is always represented as ASCII code number. the return type of read is int to be able to return -1 if nothing is read.

@Joshua: this answer makes no sense; read and try to understand the comments.


text:
How to save the SHA256 with HMAC into a variable instead of serial print?
#include "sha256.h"

uint8_t hmacKey1[]={
0x65,0x63,0x73,0x74,0x61,0x63,0x79
};

void printHash(uint8_t* hash) {
int i;
 for (i=0; i<32; i++) {
   Serial.print("0123456789abcdef"[hash[i]>>4]);
   Serial.print("0123456789abcdef"[hash[i]&0xf]);
  }
 Serial.println();
}

void setup() {
   uint8_t* hash;
   uint32_t a;

 Serial.begin(9600);

 // HMAC tests
  Serial.println("Test: RFC4231 4.2");

Serial.print("Result:");
Sha256.initHmac(hmacKey1,20);
Sha256.print("Hi There");
 //My TRIAL ATTEMPT
 int i;
 for (i=0; i<32; i++) {
 hash[i] =Sha256.resultHmac();
 Serial.println(hash[i]);
 }
}

How do I save the hashed result into a variable? I disregarded the Printhash function above and tried it with my own code but it displays
 sketch_feb14a:32: error: invalid conversion from 'uint8_t*' to 'unsigned char'

I don't understand the printhash function above and found little to no documentation on the web. I'm thinking of using AES library but I guess it's more complicated over here. The above code is based on Spaniako's CryptoSuite here
Heading

The  printHash function takes the upper and lower 4 bits of each byte, and uses them as an index to the string of hex digits.

My solution was making a new function that returns a String with the hash
String GetHash256(uint8_t* hash) {
    char tmp[16];
    String sHash256 = "";

    int i;
    for (i=0; i<32; i++) {
        sprintf(tmp, "%.2X",hash[i]);
        sHash256.concat(tmp);
    }

    return sHash256 ;
}

The hash is a series of binary digits. They are usually represented in hexadecimal form for readibility. You are just printing out the raw bytes, which will give a series of random ASCII characters. Some of these may be control characters which interfere with serial port communication.

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


text:
Arduino Nano not recognized by Mabook Pro M1
I am new to Arduino and I have ran into an issue. When I first tried to plug the arduino nano (after market, from ebay) into my computer (Macbook pro M1), nothing happened. Then I downloaded the cp210xVCP Driver. After that, when I plugged in the nano, the /dev/cu.usbserial- 1110 appeared. But when I try to get board info noting happens. It's like the computer recognize there is something, but does not know what. I believe Arduino is not fully compatible for M1 macbooks, but is there something I can do to fix this?

Have you tried uploading a sketch now your board is detected by the OS?

My Arduino clones don't give any Board Info either, so this might be not related to just M1 Macbooks...

Majenko and Python Schlange have the right of it I think. This is a common and well documented phenomenon. Check out the comments on the Arduino forum by the arduino team which explain PIDS and VIDS on USB equipment and why the clones appear differently. It shouldn’t (all going according to plan) make a difference other than the board information not being present as you’ve noted. That’s why Majenko is suggesting you go ahead and upload a sketch. The Blink example sketch is frequently used for this as a first board test when you receive something new.
See also USB FT232 driver on M1 mini for more information about checking USB ports on the Mac.


text:
Can I pass data from an Arduino Nano to a Websocket Server via USB?
I have an Arduino Nano, and a local Java WebSocket server (ws://localhost:8888) run by a .jar file on my computer.
I'm wondering if it's possible to send data (text, numbers etc.) from the Arduino Nano to the WebSocket server via USB cable (USB-A to USB Mini, one that normally powers the Nano).
If so, what do I need to do it?
A quick Google for WebSocket Arduino libraries reveals:
Websockets and Arduino Websocket Fast, but looking at the examples, the former uses Ethernet.h and the latter uses Wifi.h, and I'm unsure if my board is compatible with that without other modules.

I don't know the possibilities you have in WebSocket, but the ordinary way to communicate with an Arduino (when it does not have a Wifi or Ethernet HAT) is via Serial. You can use basically any serial communication library to send strings from/to the Arduino.

I figured as much, I'm trying the SerialPort library and facing an issue, see here: https://github.com/serialport/node-serialport/issues/2297

You fail to describe what error you get and what doesn't work.

It's in the title of the issue, and mentioned again in the issue

I ended up using Python to bridge Serial to WebSocket. I wanted flexibility in sending from WebSocket back to Serial too, so I didn't try a prepackaged solution like https://github.com/RandomStudio/serial-to-websocket

it is what RaulG recommended some days ago. it would be nice to accept his answer and not to write a new one

As @Majenko already said the ATmega328 uses a serial connection to communicate. Another chip on the board translates the serial data to USB-Format and the other way around. This enables your computer to interact with the main chip on the Nano (ATmega328).
To solve your problem you might try using something like this simple serial-to-websocket node-server that listenes to data coming in from a serial port and sends it out over WebSocket.

No, you can't. The Arduino has a serial connection, not a network connection. If the Java program is of your own devising you would need to rewrite it to use serial instead of (or as well as) WebSockets. Either that or write a separate piece of software for your computer to go between the Arduino's serial connection and the WebSockets interface.


text:
How to fix serial communication problem between Arduino UNO and sim900A
I've connected the arduino UNO to the sim900a. But after checking the serial communication between the two I keep getting these output.

Here is the connections and code that I used
#include <SoftwareSerial.h>
SoftwareSerial SIM900A(2, 3);
// Connect the SIM900A TX to Arduino pin 2 RX.
// Connect the SIM900A RX to Arduino pin 3 TX.
char c = ' ';
void setup()
{
 // start th serial communication with the host computer
 Serial.begin(9600);
 while (!Serial);
 Serial.println("Arduino with SIM900A is ready");
 // start communication with the SIM900A in 9600
 SIM900A.begin(9600);
 Serial.println("SIM900A started at 9600");
 delay(1000);
 Serial.println("Setup Complete! SIM900A is Ready!");
 }
 void loop()
 {
  // Keep reading from SIM900 and send to Arduino Serial Monitor
  if (SIM900A.available())
  { c = SIM900A.read();
    Serial.write(c);
   }
  // Keep reading from Arduino Serial Monitor and send to SIM900A
  if (Serial.available())
  { c = Serial.read();
   SIM900A.write(c);
  }
 }

How can I fix this?

On what baudrate does the SIm module run? I would guess you have a baudrate mismatch

SIM900 has auto baud rate detection, meaning you need to send a couple of  "AT" to the module to sync the baud rate before sending the rest. If the baudrate is sync, it will reply "OK". Also are you powering the SIM900 with your Uno? The Uno can't supply sufficient current to power the module.

Yes, I've connected 5V(arduino) to VCC(SIM900). So the problem is the lack of current in the module?

SIM900A datasheet says Single supply voltage: 3.4V – 4.5V and while transmitting current can go up to 2A. None of these can be provided by the UNO.

@hcheung I can see no reference to auto baud for the SIM900A. Do you have a reference? All I can find is that it has a default baud rate of 9600 and that can be configured using AT commands to between 9600 and 115200 baud.

@Majenko See section 3.7.1 of SIM900 hardware design reference (or page 34), in fact nearly all SIMCOM modules are capable of auto baud rate.

You are using the wrong pins on the SIM900A to communicate with your Arduino.
That specific module has a MAX232 interface on it to convert TTL UART to RS232. That is not compatible with the Arduino unless you add another MAX232 to undo the conversion that the one on the board does.
Instead you need to use the other 3-pin header at the other end of the board.  It should (according to this site) be wired like this:

Of course you can use other pins than 0/1 on your Arduino, as long as you connect them to the right place on the SIM900A module as shown in that diagram.
Also note what I take to be a pair of jumpers bridging pins on the header you're currently connecting to (ring around them in the diagram).


text:
MPU 6050 only reads 0 in output
I am new to using MPU 6050. I am stuck at a basic code of getting readings from the sensor. The code I used is attached below. Its the one with GY 521 breakout board. Concluding that my sensor is broken I have changed sensor and now using the third one. Still no luck. FYI I have run the i2c scanner code to check whether arduino(nano) can detect the sensor. The code responds to all the sensors I tried. I have no clue what I am doing wrong. If someone could provide some suggestions it would be helpful
    MPU6050 Triple Axis Gyroscope & Accelerometer. Simple Gyroscope Example.
    Read more: http://www.jarzebski.pl/arduino/czujniki-i-sensory/3-osiowy-zyroskop-i-akcelerometr-mpu6050.html
    GIT: https://github.com/jarzebski/Arduino-MPU6050
    Web: http://www.jarzebski.pl
    (c) 2014 by Korneliusz Jarzebski
*/

#include <Wire.h>
#include <MPU6050.h>

MPU6050 mpu;

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

  // Initialize MPU6050
  Serial.println("Initialize MPU6050");
  while(!mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G))
  {
    Serial.println("Could not find a valid MPU6050 sensor, check wiring!");
    delay(500);
  }

  // If you want, you can set gyroscope offsets
  // mpu.setGyroOffsetX(155);
  // mpu.setGyroOffsetY(15);
  // mpu.setGyroOffsetZ(15);

  // Calibrate gyroscope. The calibration must be at rest.
  // If you don't want calibrate, comment this line.
  mpu.calibrateGyro();

  // Set threshold sensivty. Default 3.
  // If you don't want use threshold, comment this line or set 0.
  mpu.setThreshold(3);

  // Check settings
  checkSettings();
}

void checkSettings()
{
  Serial.println();

  Serial.print(" * Sleep Mode:        ");
  Serial.println(mpu.getSleepEnabled() ? "Enabled" : "Disabled");

  Serial.print(" * Clock Source:      ");
  switch(mpu.getClockSource())
  {
    case MPU6050_CLOCK_KEEP_RESET:     Serial.println("Stops the clock and keeps the timing generator in reset"); break;
    case MPU6050_CLOCK_EXTERNAL_19MHZ: Serial.println("PLL with external 19.2MHz reference"); break;
    case MPU6050_CLOCK_EXTERNAL_32KHZ: Serial.println("PLL with external 32.768kHz reference"); break;
    case MPU6050_CLOCK_PLL_ZGYRO:      Serial.println("PLL with Z axis gyroscope reference"); break;
    case MPU6050_CLOCK_PLL_YGYRO:      Serial.println("PLL with Y axis gyroscope reference"); break;
    case MPU6050_CLOCK_PLL_XGYRO:      Serial.println("PLL with X axis gyroscope reference"); break;
    case MPU6050_CLOCK_INTERNAL_8MHZ:  Serial.println("Internal 8MHz oscillator"); break;
  }

  Serial.print(" * Gyroscope:         ");
  switch(mpu.getScale())
  {
    case MPU6050_SCALE_2000DPS:        Serial.println("2000 dps"); break;
    case MPU6050_SCALE_1000DPS:        Serial.println("1000 dps"); break;
    case MPU6050_SCALE_500DPS:         Serial.println("500 dps"); break;
    case MPU6050_SCALE_250DPS:         Serial.println("250 dps"); break;
  }

  Serial.print(" * Gyroscope offsets: ");
  Serial.print(mpu.getGyroOffsetX());
  Serial.print(" / ");
  Serial.print(mpu.getGyroOffsetY());
  Serial.print(" / ");
  Serial.println(mpu.getGyroOffsetZ());

  Serial.println();
}

void loop()
{
  Vector rawGyro = mpu.readRawGyro();
  Vector normGyro = mpu.readNormalizeGyro();

  Serial.print(" Xraw = ");
  Serial.print(rawGyro.XAxis);
  Serial.print(" Yraw = ");
  Serial.print(rawGyro.YAxis);
  Serial.print(" Zraw = ");
  Serial.println(rawGyro.ZAxis);

  Serial.print(" Xnorm = ");
  Serial.print(normGyro.XAxis);
  Serial.print(" Ynorm = ");
  Serial.print(normGyro.YAxis);
  Serial.print(" Znorm = ");
  Serial.println(normGyro.ZAxis);

  delay(10);
}

Could you provide a schematic of how you connected everything together? The MPU-6050 is a 3.3 V device while the Arduino is 5 V. Also the GY 521 has an onboard 3.3 V regulator that should be supplied with 5 V rather than 3.3 V. More info on Arduino Plaground and schematic diagram

I hope it is useful for debugging ...
Only a sketch I found (here), not remembering if I have tested ...
// MPU-6050 Short Example Sketch
// By Arduino User JohnChi
// August 17, 2014
// Public Domain
#include<Wire.h>
const int MPU_addr=0x68;  // I2C address of the MPU-6050
int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;
void setup(){
  Wire.begin();
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x6B);  // PWR_MGMT_1 register
  Wire.write(0);     // set to zero (wakes up the MPU-6050)
  Wire.endTransmission(true);
  Serial.begin(9600);
}
void loop(){
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU_addr,14,true);  // request a total of 14 registers
  AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
  AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
  AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
  Tmp=Wire.read()<<8|Wire.read();  // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
  GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
  GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
  GyZ=Wire.read()<<8|Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
  Serial.print("AcX = "); Serial.print(AcX);
  Serial.print(" | AcY = "); Serial.print(AcY);
  Serial.print(" | AcZ = "); Serial.print(AcZ);
  Serial.print(" | Tmp = "); Serial.print(Tmp/340.00+36.53);  //equation for temperature in degrees C from datasheet
  Serial.print(" | GyX = "); Serial.print(GyX);
  Serial.print(" | GyY = "); Serial.print(GyY);
  Serial.print(" | GyZ = "); Serial.println(GyZ);
  delay(333);
}

There is also a long example sketch ...

You do not tell us what is the problem so my guess is address or level.
If you get "Could not find a valid MPU6050 sensor, check wiring!" this is an address problem. By default MP6050 uses x068 as I2C address. If you have something else connected to the bus, there might be a conflict. If so, connect AD0 to 3.3V (pull-up with a 2.2kOhms resistor) to set address to 0x69 (use I2C scanner in /example/wire to make sure).
If you see zeros, this might be a logic level problem:
To elaborate on the previous answer, the MP6050 is a 3.3V device. The GY 521 circuit has a voltage regulator (5V->3.3V) bUt on output it still uses 3.3V TTL logic level. With some noise, bad contacts or long wires, the Arduino may fail to read the I2C properly. Had similar problems, solved using a bidirectional logic level shifter between a Uno and the MPU6050. You can get pre-assembled 4-channels board (same size as GY521 board) for ~ 1US$. I hope this helps


text:
IR output won't stop
So I basically tried to control a Servo motor with an IR Remote. I'm a complete newbie in arduino programming but I just took some things from other scripts and tried them out until It worked, and it kinda did but my main problem is that as soon as I press a button the action is exectuted but the command like left arrow on the remote control just spams over and over again so I cannot have an action after that one
`
#include "IRremote.h"
#include "IR.h"
#include <Servo.h>

int receiver = 11;

IRrecv irrecv(receiver);     // create instance of 'irrecv'
decode_results results;      // create instance of 'decode_results'
Servo myservo;

void setup() {
  Serial.begin(9600);
  Serial.println("IR Receiver Button Decode");
  irrecv.enableIRIn();
  myservo.attach(9);
  myservo.write(0);
}

void loop()
{
if (irrecv.decode(&results))
 {
   //  irrecv.resume();   // Receive the next value
  // }
  //if (results.value == 0xFF629D)  // change according to your IR remote button number
  //  {
    //  myservo.write(0);
      //delay(15);
   // }
    //if (results.value == 0xFF629D)  // change according  to your IR remote button number
    //{
     // myservo.write(30);
    //delay(15);
    //}

      switch(results.value)
  {
  case 0xFFA25D: Serial.println("POWER"); break;
  case 0xFFE21D: Serial.println("FUNC/STOP"); break;
  case 0xFF629D: Serial.println("VOL+"); break;
  case 0xFF22DD: Serial.println("FAST BACK");
  myservo.write(90);
  delay(15);
  break;
  case 0xFF02FD: Serial.println("PAUSE");    break;
  case 0xFFC23D: Serial.println("FAST FORWARD");
  break;
  case 0xFFE01F: Serial.println("DOWN");    break;
  case 0xFFA857: Serial.println("VOL-");    break;
  case 0xFF906F: Serial.println("UP");    break;
  case 0xFF9867: Serial.println("EQ");    break;
  case 0xFFB04F: Serial.println("ST/REPT");    break;
  case 0xFF6897: Serial.println("0");    break;
  case 0xFF30CF: Serial.println("1");    break;
  case 0xFF18E7: Serial.println("2");    break;
  case 0xFF7A85: Serial.println("3");    break;
  case 0xFF10EF: Serial.println("4");    break;
  case 0xFF38C7: Serial.println("5");    break;
  case 0xFF5AA5: Serial.println("6");    break;
  case 0xFF42BD: Serial.println("7");    break;
  case 0xFF4AB5: Serial.println("8");    break;
  case 0xFF52AD: Serial.println("9");    break;
  case 0xFFFFFFFF: Serial.println(" REPEAT");break;
  default:
    Serial.println(" other button   ");`

That's my code, and whenever I press like Fast Back I can't do anything else and the Serial Monitor is just full of Fast Back

Put back in the irrecv.resume() that you commented out?

what happens if you press VOL+?

@Majenko Thank you very much, ther commented out one acutally had nothing to do with it but I had to add one at the end of the switch


text:
What do i do to get my bluetooth module to light up?
I'm very new to arduino and am doing my first project, a bluetooth run robot. When i plugged in my module to my laptop to upload the code, the module lights up, and afterwards, i was able to run it on my 12v battery. However, later on, my module stopped working suddenly. It came on once after that, but was on AT config and blinked out soon after. Is this problem because I have been using my battery for a month now without a recharge or because its connected to too many devices or because of a faulty bluetooth module

How is everything connected? Please show a wiring diagram

are you asking if your battery is dead?


text:
Using TX/RX serial pins to communicate over USB
I'm using an Arduino Nano with an Atmega 328p.
I would like to attach and use a different USB port instead of the builtin one for supplying power, serial debugging and uploading code.
Currently my board is recieving power from the USB port using vin, but I would like to know how I can get the Arduino to use serial communication with the TX/RX pins and the data+ and data- pins on the USB. I'm especially interested in knowing if I can upload new code to the board through TX/RX.
The official page for the Nano says that the serial communication is handled by an FTDI FT232RL chip, which as I understand, translates the signal from the builtin USB to serial. Is there any way that I can use this chip to communicate over the TX/RX pins instead of builtin USB?
Online documentation about this subject is really lacking, and of the few opinions that I've found, many are conflicting. I would really appreciate any help with this, thanks.

why do you want to use a second FTDI?

Are you looking for something like this: https://www.obdev.at/products/vusb/index.html ? Not quite clear to me why you don't want to use the builtin FTDI and associated Adruino tools

Instead of moving the data connection, wouldn't it be easier to add a second USB port for the power supply and connect it to the 5V pin?

Unrelated; you shouldn't connect the the 5V from the USB to the VIN pin. Connect it directly to the 5V/Vcc pin. The VIN pin requires at least 7 volts, and will regulate this down to 5V. Since you already have 5V you can bypass the regulator.

There is no "built-in USB" on the Nano. There is only the FT232RL chip which talks USB. That chip is connected directly to the TX/RX pins inside the board.
You are already communicating over the TX/RX pins through the FT232RL to the USB.
Yes, you could use your own FT232RL (or FT232-like) board to communicate between USB and the TX/RX pins, but that will be exactly the same as using the one built in to the board - but without the convenience, and with the addition of more wires and expense.  So pointless, unless the current USB connection is damaged in some way.

Ah, sorry, my mistake.
So, if I wanted to add an additional USB port, I would also need an additional USB to serial converter chip? Does the included chip only work with the included USB port?
Sorry if my question sounded a bit odd, I'm a student and this is more of a learning exercise. Thanks for the helpful answer!

If you want to add an extra USB port you will have to use SoftwareSerial to communicate with some FT232-like board through other pins that TX/RX.


text:
Arduino Nano not recognized on Windows 10
For some weeks my latest dozen of Nano's isn't recognized any more by Win 10 computer: After two days of experiments I have suspicions:

Is there any change in Win10 since all Arduinos now are only shown in "Hidden devices" in the device manager? However, my old Uno and also an old Nano are still working despite of that... (The old nano has a chip named CH340G on the downside; the new nano's chip has no name at all).
The Nanos I'm trying to program now I got from China (order date 26 sep 2019) and they are said to be compatible with CH340SER. In fact I have programmed several of them early this year - turning back to them in October, upload was no longer possible.
In the meantime, I have switched from Arduino IDE 1.8.6 to 1.8.13 - however, I guess this is not the reason for my troubles since not even Windows recognizes the device when I plug it in...
Any advices to this problem?
Dieter

With Chinese clones the best one can ever say is "Maybe..." - and it sounds like you have a clone of a clone - so the best one can say there is "um... probably not...!"

You're lucky it's worked this long.  You get what you pay for. Pay for crud and you get crud.

I've had the same troubles - but it's not Windows 10 being the guilty part.
What kind of Arduino are you using? If it's a Nano (i.e. ATmega328P) then try
selecting "Nano (Old bootloader)" - this works - at least for me.
Regards Dieter


text:
Reading JSON from Arduino over serial in python and writing to a JSON file on computer
I'm fairly new to Arduino so I used a sample code before integrating this into my main code. I'm printing my value in a JSON format over serial. My Arduino outputs this and the python receives this and prints it in the same format
{

"value" : 5

}

but when I use python to try writing to a JSON file on my computer, I'm not getting the same JSON format. Can anyone figure out what's wrong? I need to write to my JSON file in JSON format, but instead, I'm getting this format written in my JSON file "  \"value\": 5\r\n" instead of {"value: 5"}. Another problem I'm getting is that sometimes the values I get in my JSON get cut off so sometimes I end up with \r\n" or other parts of the current output. My goal is to get the python code to overwrite the JSON file in real-time, so whenever I open the JSON file, the entire output should be there in the correct JSON format. Any help is appreciated, thank you.
Arduino Code:
#include <ArduinoJson.h>

int analogPin = 3;
int data = 0;
char userInput;

StaticJsonDocument<100> testDocument;
char buffer[100];

void setup(){

  Serial.begin(9600);          //  setup serial

  StaticJsonDocument<100> testDocument;

  testDocument["sensorType"] = "Temperature";
  testDocument["value"] = 10;

  char buffer[100];

  serializeJsonPretty(testDocument, buffer);

  Serial.println(buffer);

}
int(i)=1;
void loop(){

    testDocument["value"] = i;

    serializeJsonPretty(testDocument, buffer);

    Serial.println(buffer);

    i=i+1;
 }

Python Code:
import serial
import json
import time

ser = serial.Serial('COM4', baudrate = 9600, timeout=1)

while 1:

    data = (ser.readline().decode('ascii')) #split('\r\n')

    #j = json.loads(data)

    file = "C:/Users/Mike/Desktop/test.json"

    my_data_file = open(file, 'w')

    with open(file1, "w") as my_data_file :
        json.dump(data, my_data_file)

    print(data)

Is the JSON correctly send via serial? Please look at the output of the Serial Monitor, to check that. Having backslashes in there suggest, that the ASCII characters don't get escaped correctly. The python code is not really our territory (as here is Arduino SE). Though: you have commented out the json.loads(data) line. Currently you are trying to json dump a string, which should be a data structure. if you want to dump the json, you first need to load it. Or you could completely ditch the python json and just write the received json string to the file

Yes, when I print the data I'm receiving the same output as my serial monitor, just not in the JSON file. I'll take a look at the code again and look at what you suggested. I'll try posting to a more suitable group for the python as well. Thank you for your help.

@chrisl I looked at what you said and so every time I run the code, I get a JSON output in the serial monitor and when I print the data in python. However, when I write the data to the JSON file it's in that weird format with the quotations on the outside and backslash symbol in between. I couldn't find a way to write it in the JSON format. I used a different arduino code to try it and I'm still getting the same thing, no luck.

I don't know, what you are doing with your python code. But in the above code, you should do the following: Read all available data, until you have all you need, not just one line at a time. Then use the line j = json.loads(data) to get the data as python data structure (data must be a string with the complete json string). Then you can dump j to the file. You are getting the masking backslashes, because you are currently trying to dump a string instead of the data structure. And when saving a string in json, the json module must escape the special characters like "

okay, I think that's where I'm getting my errors with the special characters. I'll take a look. Thank you for helping out.


text:
How to drive motors and use an ultrasonic sensor simultaneously?
I have a L298 motor driver, which I coded with an Arduino Nano.
The code is very simple at the moment:
// connect motor controller pins to Arduino digital pins
// motor one
int enA = 10;
int in1 = 9;
int in2 = 8;
// motor two
int enB = 5;
int in3 = 7;
int in4 = 6;
void setup()
{
  // set all the motor control pins to outputs
  pinMode(enA, OUTPUT);
  pinMode(enB, OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);
  pinMode(in3, OUTPUT);
  pinMode(in4, OUTPUT);
}

void demoTwo()
{
  // this function will run the motors across the range of possible speeds
  // note that maximum speed is determined by the motor itself and the operating voltage
  // the PWM values sent by analogWrite() are fractions of the maximum speed possible
  // by your hardware
  // turn on motors
  Motors_FWD_PWM_Initialize();

  // accelerate from zero to maximum speed
  for (int i = 0; i < 256; i++)
  {
    analogWrite(enA, i);
    analogWrite(enB, i);
    delay(20);
  }
  // decelerate from maximum speed to zero
  for (int i = 255; i >= 0; --i)
  {
    analogWrite(enA, i);
    analogWrite(enB, i);
    delay(20);
  }
  // now turn off motors
  MotorsOff();
}
void loop()
{
  demoTwo();
  delay(1000);
}

void Motors_FWD_PWM_Initialize()
{
  digitalWrite(in1, HIGH);
  digitalWrite(in2, LOW);
  digitalWrite(in3, HIGH);
  digitalWrite(in4, LOW);
}

void MotorsOff()
{
  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);
}

Currently I have two questions:
Q1: I have an ultrasonic sensor, how can I write the code so that the motors work and 'keep an eye out' with the ultrasonic sensor simultaneously? i.e. When a certain proximity is reached I would like the robot to stop.
Q2: Also I would like my robot to 'rove' around. How can I make it so? I was thinking having a number of subroutines, and making the arduino randomly choose one.

For the first question, you could simply implement an interrupt routine to regularly check the status of your sensor and when it achieves the desired threshold it triggers the action to stop the motor.
You can achieve this by setting timer1. There is a library here for example, where you set the period to execute a desired function, when some distance is detected you just stop the motors.
The second question could be done exactly like you said. Say you have some paths saved in memory, you can just create some options for them and execute whenever you want using switch/case command.
http://playground.arduino.cc/code/timer1

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


text:
DS1302 as a counter/count-up timer
I would like to use the DS1302, as a count up timer.
My goal is to have the arduino time the amount of me driving my car.
So it DS1302 will be used a count-up timer ie accumulate time. however when the car is switched off, I don't want to lose the value, and when I use my car again I would like to the time to continue accumulating. The resolution can be in minutes, as this will probably be the best.
I would like something like an odometer of a car, except its going to be the time, instead of distance.
Q: Can this be done with the DS1302 Module? and also how can I do this? Is there a sample code for a count-up timer?

The Arduino can do the whole task by itself well enough.

In theory yes, but in practice it's become unreliable.

In practice the DS1302 is unreliable - as noted on the page you reference. Perhaps starting with "My Arduino does not time things as well as it should be perfectly able to - here is what I have tried in adequate detail - any ideas?" question may be a good start. Adding known bad hardware to a bad software or hardware issue may not help. || Arduino needs to be powered on when car is off OR stay on long enough to save data to non volatile memory. Either should be "easy enough".

"I don't want to lose the value" -> store it in non-volatile memory before shutting down the Arduino or in regular intervals -> e.g. EEPROM -> look for questions how to do this on this site / google.

What's the maximum time you want to record? Days, months or years?

@Ricardo it would be days, if the average engine life is 400,000km at an average speed of 40 km/h that would result to 400,000/50=10,000 hours of use, 10,000 hours = 417 days to record. But I am thinking this number would be significantly less. For example if the average speed is 45 kph its 370 days etc. If the engines life is only 250,000km @ 40kph = 260 days to record.

Do you mean only accumulate during powered/driving, or also during standing still?
If the former, just get the start time in setup, then in loop continuously get the time and calculate the difference between it and the time read in setup. Since you don't know when power is lost you need to continually write the elapsed time to some form of non-volatile memory. You could use the Arduinos EEPROM, but that can wear out over time. It's better the use the DS1302s 31 byte of battery backed RAM. Next time the arduino starts up you need to read out this value and add this to the difference.
In case of the latter, you can halt the DS1302 so it stops incrementing time.

I'm only after the time the keys are on the ignition, I don't care if they're sitting my car and listening to the radio or driving on the freeway, I'm just after the time the car is 'on'. Q: Is there any alternative methods in obtaining this data/statistics?

In that case use the first part of my answer. If you don't mind a bit less accuracy, you can even drop the DS1302 entirely. Just use the arduino millis function for tracking time. The crystal on the arduino is not that accurate, but you can measure the inaccuracy and account for this in code. You can probably get to less than 1 minute of drift per day.

What you're describing is the equivalent of a digital Hobbs hour meters. You can read up about them if your are interested. The old ones (not digital in today's sense) clicked an odometer-like movement every 0.1 hours (typically). I don't think you need a real-time clock module as long as you're not interested in when you drove the car, but only in the accumulated duration.
A simple way would be a 1-minute delay loop that increments a counter and writes it to EEPROM. The EEPROM has a write-endurance spec of 100,000 writes, equivalent to over 800 hours, used this way. You'll lose the last fraction of a minute, whether it's a few seconds or nearly a while minute, whenever you shut down the Arduino. There are ways around this, if it matters, but that's an "exercise left for to the reader" as my textbooks used to say. Clock your micro with a crystal, not with its internal resonator, for best accuracy.

When I rent out my car, I already have an analogue gauge for reference, The only way of seeing it would be physically being next to the car. I want the arduino to sms (gsm shield) me the hours every so often (every 8 minutes). Q: Do you know if the digital hobbs hour meter can be tapped into by the Arduino?

I've no idea, but wouldn't it be much simpler to let the Arduino do the whole job - timing + communication? I didn't mean to suggest you should install a Hobbs meter; just that you might get some ideas by reading about them. I think an AVR chip and the GSM module would probably do just what you want.

The comms are at a later stage -I just want to do the timing at the moment. You might be right, letting the Arduino do all the work might be easier.


text:
Issue understanding timestamp generated using millis() function
I have this code uploaded to an Arduino Uno which is connected to a gyroscope and storing the data on an SD card. The code is from the OEM.
The delay() function was set to 500 by default but this was changed to 10 in order to get an output frequency of 100Hz.
The millis() function was added to observe whether the 100Hz frequency was being maintained.
#include <Wire.h>
#include <SPI.h>
#include <SD.h>
File myFile;

#define CTRL_REG1 0x20
#define CTRL_REG2 0x21
#define CTRL_REG3 0x22
#define CTRL_REG4 0x23
int Addr = 105; // I2C address of gyro
int x, y, z;

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

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

  if (!SD.begin(10)) {
    Serial.println("initialization failed!");
    while (1);
  }
  Serial.println("initialization done.");

 writeI2C(CTRL_REG1, 0x1F); // Turn on all axes, disable power down
 writeI2C(CTRL_REG3, 0x08); // Enable control ready signal
 writeI2C(CTRL_REG4, 0x80); // Set scale (500 deg/sec)
 delay(100); // Wait to synchronize
}
void loop(){
 myFile = SD.open("test.txt", FILE_WRITE);

 getGyroValues(); // Get new values
 // In following Dividing by 114 reduces noise
 Serial.print(millis());
 Serial.print(" Raw X:"); Serial.print(x / 114);
 Serial.print(" Raw Y:"); Serial.print(y / 114);
 Serial.print(" Raw Z:"); Serial.println(z / 114);

 myFile.print(millis());
 myFile.print(" Raw X:"); myFile.print(x / 114);
 myFile.print(" Raw Y:"); myFile.print(y / 114);
 myFile.print(" Raw Z:"); myFile.println(z / 114);

myFile.close();

 delay(10); // Short delay between reads
}
void getGyroValues () {
 byte MSB, LSB;
 MSB = readI2C(0x29);
 LSB = readI2C(0x28);
 x = ((MSB << 8) | LSB);
 MSB = readI2C(0x2B);
 LSB = readI2C(0x2A);
 y = ((MSB << 8) | LSB);
 MSB = readI2C(0x2D);
 LSB = readI2C(0x2C);
 z = ((MSB << 8) | LSB);
}
int readI2C (byte regAddr) {
 Wire.beginTransmission(Addr);
 Wire.write(regAddr); // Register address to read
 Wire.endTransmission(); // Terminate request
 Wire.requestFrom(Addr, 1); // Read a byte
 while(!Wire.available()) { }; // Wait for receipt
 return(Wire.read()); // Get result
}
void writeI2C (byte regAddr, byte val) {
 Wire.beginTransmission(Addr);
 Wire.write(regAddr);
 Wire.write(val);
 Wire.endTransmission();
}

However, these are the first few values that were saved onto the "test.txt" file:

This shows a change in time of approximately 0.03s between values and therefore a frequency of 33.3Hz. Does anyone know why this is the case?

every command in the program takes time to execute ... some longer than others

You are opening and closing the file on every loop iteration. That looks like a bad idea...

29 characters at 9600 baud is about 0.030s/loop().

The delay just adds time to the overall runtime of the loop() function. So you would have a frequency of 100Hz only if all the other code would take zero time. And what you are doing there does take a significant amount of time (communicating over I2C and SPI, writing to the SD card). Thus your overall runtime of one loop() iteration is considerably longer. From your data we can even say how much longer it took. You measured a 30ms interval between the samples. 10ms of that is the delay. So the rest of the code took 20ms to execute. That also means, that with your current code you can get only up to 50Hz (by removing the delay()).
First to explain how to go with a timing situation like this lets assume the targeted frequency is possible with your code:
You have 2 options to go with timing:

Make the delay() smaller. With trail and error find a value that results in a 100Hz sampling frequency.
Use millis() directly for the timing. That way it is not important how long your code took to execute (as long as it was shorter than your sampling interval). For this you can basically copying the code from the BlinkWithoutDelay example, which uses millis() to blink an LED. You can use it to instead collect data samples and write them to the SD card.

The second option is superior and also a very important concept to understand in programming for Arduinos (or any microcontroller).

Now lets have a look at the problem with 100Hz. As explained above your current code takes too long to execute, so that you cannot reach a sample rate of 100Hz. You should use millis() to also check, which part of the code does take the most time.
I suspect that its the file writing. One way to speed this up is to only open and close the file once, instead of in every loop() iteration (as Edgar Bonet mentioned in the comments). After that I don't think you can speed this up further. A technique, that is often used in such situation, is to first collect a defined number of samples at the wanted frequency - temporarily saving them in an array - and then stop the sampling for writing to the SD card. That can give you short bursts of faster sampling at the cost of needing to wait for writing after that. It depends on your application if that is OK for you.
For the I2C you might be able to speed it up a bit. If your gyroscope is supporting that you can set the I2C clock signal to a higher frequency, for example 400kHz instead of 100kHz, via Wire.setClock(). Note that only specific values are allowed with this function and if a value works depends on your microcontroller. I think the Uno supports up to 400kHz.
You need to test by yourself if you can get the execution time below 10ms per loop() iteration.

Your loop() function takes many milliseconds to execute because reading gyroscope, opening file on SD, and writing on serial are slow and blocking operations. On top of this, you add delay(10), so your final frequency will always be lower than 100Hz.
You should use the while-millis pattern, a standard and simple solution to overcome this issue. Here a complete explanation about it.


text:
LED brightness variations
I'm using two different types of code and noticing that in the first set up the last LED is dimmer than the rest. Then in the second set up, the first LED is brighter than the rest. I would like to know what is causing it and how I may fix it. My ultimate goal is to wire 30 LEDs on an Arduino Mega and time them to a sequence. I'm building the project from the ground up starting with 3 LEDs on an Arduino Uno. I really appreciate your insights.
The first set up is using a pushbutton as a switch to turn on 3 LEDs in a timed series, using 220ohm resistors. The first two LEDs wired to pins 2 and 4 are visibly bright while the last you can barely see a little dot of light.

Here's the code for it:
int ledState = 0;
int ledPin1 = 2;
int ledPin2 = 4;
int ledPin3 = 7;
int buttonState = 0;
const int buttonPin = 12;
int buttonNew;
int buttonOld;
int fiveInterval = 3000;
int oneInterval = 1000;

void setup() {
  Serial.begin(9600);
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(buttonPin, INPUT);

}

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

  if(buttonOld == 0 && buttonNew == 1){
    if(ledState == 0){
      digitalWrite(ledPin1, HIGH);
      delay(fiveInterval);
      digitalWrite(ledPin2, HIGH);
      delay(fiveInterval);
      digitalWrite(ledPin3, HIGH);
      ledState = 1;
//      for(int i ){
//
//      }
    }else{
      digitalWrite(ledPin1, LOW);
      digitalWrite(ledPin2, LOW);
      ledState = 0;
    }
  }
  buttonOld = buttonNew;
  delay(100);
}

The second set up is some code I borrowed from a tutorial. The 1st LED (wired to pin 2) is several times brighter than following LEDs. This one is a timed on/off of 3 LEDs, using 220ohm resistors.

Here's the code for it:
#define LED_PIN_1 2
#define LED_PIN_2 4
#define LED_PIN_3 7
#define LED_NUMBER 3
byte LEDPinArray[LED_NUMBER] = { LED_PIN_1,
                                 LED_PIN_2,
                                 LED_PIN_3 };
int LEDIndex = 0;
void initAllLEDs()
{
  for (int i = 0; i < LED_NUMBER; i++) {
    pinMode(LEDPinArray[i], OUTPUT);
  }
}
void powerOnSelectedLEDOnly(int index)
{
  for (int i = 0; i < LED_NUMBER; i++) {
    if (i == index) {
      digitalWrite(LEDPinArray[i], HIGH);
    }
    else {
      digitalWrite(LEDPinArray[i], LOW);
    }
  }
}
void toggleNextLED()
{
  LEDIndex++;
  if (LEDIndex >= LED_NUMBER) {
    LEDIndex = 0;
  }
  powerOnSelectedLEDOnly(LEDIndex);
}
void setup()
{
  initAllLEDs();
  digitalWrite(LEDPinArray[LEDIndex], HIGH);
}
void loop()
{
  delay(1000);
  toggleNextLED();
}

rightmost LED does not have a resistor in series

the code would be simpler if you use arrays ... ledPin[1], ledPin[2], etc ... that way you can use a loop to turn on all that have an index that is less than or equal to LEDIndex

You're not setting all the LEDs to be OUTPUT, so one is being powered through the internal pullup resistor.

Thanks everyone for your helpful suggestions. I've corrected the errors and also spent some time on writing the code with arrays, and now I'm able to time my 30 LEDs with equal brightness in a sequence. Now on to the next challenge...controlling these with two pushbuttons! :)


text:
Arduino ESPTelnet.h library read data from cmd screen
I am new to Arduino. I used Arduino IDE for upload code to ESP8266 module. I wrote an ATM application on the tiva-tm4c123 board. I am trying to connect to the application from the internet using telnet and ip address. I uploaded the example code of the ESPtelnet library to the ESP8266 module and connected the esp wifi module to the tm4c123 card by using uart. The ESP8266 module sends the data from the tiva card to the putty screen that I connect via telnet. But it does not transfer what I write from the putty screen to the tiva card. I couldn't find a function like telnet.read(). Is there a telnet function that will read the data from the Putty screen? I searched a lot but couldn't find it. If I find this function, I know that I can send the read data to the tiva card with Serial.write(telnet.read).ESP's RX and TX are connected to the tiva card. I created a wireless connection to the Putty screen.  When a char or string is entered on the telnet screen, it will send it to the tiva card with Serial write from the TX of the ESP8266.I want to write a code that will run in the following logic.
 if (telnet.available()) {
    Serial.print(telnet.read());
  }

Here is the example code

#include "ESPTelnet.h"

/* ------------------------------------------------- */

#define SERIAL_SPEED    115200
#define WIFI_SSID       "****"
#define WIFI_PASSWORD   "****"

/* ------------------------------------------------- */

ESPTelnet telnet;
IPAddress ip;

/* ------------------------------------------------- */

void setupSerial(long speed, String msg = "") {
  Serial.begin(speed);
  while (!Serial) {
  }
  delay(200);
  Serial.println();
  Serial.println();
  if (msg != "") Serial.println(msg);
}

/* ------------------------------------------------- */

bool isConnected() {
  return (WiFi.status() == WL_CONNECTED);
}

/* ------------------------------------------------- */

bool connectToWiFi(const char* ssid, const char* password, int max_tries = 20, int pause = 500) {
  int i = 0;
  WiFi.mode(WIFI_STA);
  #if defined(ARDUINO_ARCH_ESP8266)
    WiFi.forceSleepWake();
    delay(200);
  #endif
  WiFi.begin(ssid, password);
  do {
    delay(pause);
    Serial.print(".");
  } while (!isConnected() || i++ < max_tries);
  WiFi.setAutoReconnect(true);
  WiFi.persistent(true);
  return isConnected();
}

/* ------------------------------------------------- */

void errorMsg(String error, bool restart = true) {
  Serial.println(error);
  if (restart) {
    Serial.println("Rebooting now...");
    delay(2000);
    ESP.restart();
    delay(2000);
  }
}

/* ------------------------------------------------- */

void setupTelnet() {
  // passing on functions for various telnet events
  telnet.onConnect(onTelnetConnect);
  telnet.onConnectionAttempt(onTelnetConnectionAttempt);
  telnet.onReconnect(onTelnetReconnect);
  telnet.onDisconnect(onTelnetDisconnect);

  // passing a lambda function
  telnet.onInputReceived([](String str) {
    // checks for a certain command
    if (str == "ping") {
      telnet.println("> pong");
      Serial.println("- Telnet: pong");
    }
  });

  Serial.print("- Telnet: ");
  if (telnet.begin()) {
    Serial.println("running");
  } else {
    Serial.println("error.");
    errorMsg("Will reboot...");
  }
}

/* ------------------------------------------------- */

// (optional) callback functions for telnet events
void onTelnetConnect(String ip) {
  Serial.print("- Telnet: ");
  Serial.print(ip);
  Serial.println(" connected");
}

void onTelnetDisconnect(String ip) {
  Serial.print("- Telnet: ");
  Serial.print(ip);
  Serial.println(" disconnected");
}

void onTelnetReconnect(String ip) {
  Serial.print("- Telnet: ");
  Serial.print(ip);
  Serial.println(" reconnected");
}

void onTelnetConnectionAttempt(String ip) {
  Serial.print("- Telnet: ");
  Serial.print(ip);
  Serial.println(" tried to connected");
}

/* ------------------------------------------------- */

void setup() {
  setupSerial(SERIAL_SPEED, "Telnet Test");

  Serial.print("- Wifi: ");
  connectToWiFi(WIFI_SSID, WIFI_PASSWORD);

  if (isConnected()) {
    ip = WiFi.localIP();
    Serial.print(" ");
    Serial.println(ip);
    setupTelnet();
  } else {
    Serial.println();
    errorMsg("Error connecting to WiFi");
  }
}

/* ------------------------------------------------- */

void loop() {
  telnet.loop();

  // send serial input to telnet as output
  // this part read tiva and transmit to ESP
  if (Serial.available()) {
    telnet.print(Serial.read());
  }
}
//* ------------------------------------------------- */

i think that you can only send data from the keyboard ... PuTTY does not have a screen read function

try Serial.write(telnet.read());. it is better to use while than if here: while (telnet.available())

@Juraj Problem is that there is no telnet.read() or telnet.avaible() function.

ok. sorry I don't know the library. I wrote a simpler telnet server library TelneStream, but it is really only a Server class wrapped in a thin layer. Arduino esp8266 3.0 has my ArduinoWiFiServer demonstrated by the PagerServer telnet example

It appears to me that the library has been written to accept input terminated by a newline character.
    char c = client.read();
    if (c != '\n') {
      if (c >= 32) {
        input += c;
      }
    // EOL -> send input
    } else {
      if (on_input != NULL) on_input(input);
      input = "";
      }

It will keep adding characters to the input buffer until a newline character is detected, and then pass the contents to the .onInputReceived recieved handler.
If my understanding is correct, the best you can do without making alterations to the library itself is:-

  telnet.onInputReceived([](String str) {
      Serial.println(str);
  });

Again, if I'm right then the newline character will always need to be present to push the data through.
Hope this is useful.

@Juraj Precisely.

so why do you write about altering the library

@voidPointer yes, when I use this, there is data exchange, but I need to debug it to confirm that it is correct. I will get back to you.

sorry. now I see what you mean. it is a lambda

@Juraj Because it is not simply a matter of if data is available.  The newline must also be present for delivery, rather than transmitting anything received. Without that understanding it would may be consuing why data isn't pushed through.

telnet clients usually send the newline. it can be configured. the library author knows it


text:
Is it possible to control android accessibility with arduino nano?
I am trying to build an ACC device. when a button is pressed the changes should be made via android accessibility mode.
I am using arduino nano, and I don't know how to control android using arduino.

Not with a nano, unless you write some app for Android that responds to serial data.


text:
the buzzer stops sounding after a few seconds
Sorry, I'm not fluent in English.
I beg your help
I made an arduino uno project where the buzzer only turns on for 2 seconds after the light turns on. Even though the light is still on I want the buzzer to turn off after 2 seconds. I have tried several methods but I still fail.I use sensor ldr here.
can you guys help me?
    if( sensorValue <= 25 && lastBuzzer == 0)
   {
    lastBuzzer = millis();
   }
   if(sensorValue <= 25)
  {
    if (millis() - lastBuzzer < 1000L)
    {
    digitalWrite(buzzer, HIGH);
    delay(100);
    digitalWrite(buzzer, LOW);
    delay(100);

  }
  }
  else
  {
    digitalWrite(relayPin, LOW);
    lastBuzzer = 0;

  }

There is no light or 2-second-interval in your code and it won't behave like you want at all. Please post a full minimal example so we have something to work with.

still fail does not describe what happens ... please edit your post with a description of observed behavior

If there is even one sensorValue > 25 it will stop beeping and is armed again for the next beep if it goes <= 25 -- you might want to average sensor values to protect against outliers. Did you put in some Serial.println() statements to see all sensorValue values that it processes?

You need to study https://www.arduino.cc/en/Tutorial/BuiltInExamples/BlinkWithoutDelay as that gives you a way to run two timer events simultaneously. One can blink your LED, the other can sound your buzzer for two seconds.

At least give us a circuitry showing what you're doing or what you want to do.


text:
Prevent flash cloning
I need a way to prevent someone from cloning code from arduino. Without protection it can be cloned with advdudees in 2 min. I'm using atmega328p chip on nano. In this state arduino acts as a handshake for windows program i need to protect. There is nothing special or of value on arduino, but the custom handshake. One arduino for one .exe file. All arduino code is uploaded from arduino ide.
I did research and here it is.

Lock fuse bits. As i understood once locked flash and eeprom cant be read. When they are unlocked flash and eeprom are erased. I need one more arduino to act as programator.
Use some other unique hard to copy module like rfid card or bluetooth/wifi mac address. This is bad because it takes too much pins on nano.
Subtly solder 2 digital pins and set one to output and other to input. If not connected break loop.
Usb hardware dongle licence. I have no idea how to create one and it seems like some relic of the past. Custom file system or something...

I'd like to keep arduino nano for deployment.
There is no internet involved. If program had access to internet i'd just use db.
Thanks in advance.

what is your question? ... you provided a solution to the problem of preventing the copying of flash memory ... the handshake can only be protected by preventing physical access to the windows pc

I need to known if this is a good idea and would it work. I have one attempt to get it right. And if anyone has any better solutions.

So you are developing your own protection dongle. Well, why don't you simply use a proven product?

Note that setting the lock bits is pointless, while the Arduino bootloader is installed. The bootloader can still read out the program, even with the lock bits set. You'd have to remove the bootloader and upload the code using the ISP interface (ArduinoAsISP).

You could save a GUID in EEPROM that matches one in the compiled file. The sketch reads EEPROM, and compares the saved value, quitting if they don't match. This might require flashing a simple stand-alone sketch that only writes the EEPROM before flashing your main program. It's not skilled hacker-proof, but it would stop the unaltered sketch from running anywhere but the original MCU.

Using the lock fuse bits is definitely the correct step here. Unlocking is not a problem, since the memory will be erased in that step and you cannot prevent reflashing anyway.

Very important note from Gerben in the comments:

Note that setting the lock bits is pointless, while the Arduino bootloader is installed. The bootloader can still read out the program, even with the lock bits set. You'd have to remove the bootloader and upload the code using the ISP interface (ArduinoAsISP).

The lock bits only work for the ISP interface, which can be used to program the Arduino. The bootloader (which is part of the program on  the Arduino) still can read the program memory (it has to, since it is executed from there). Thus to prevent someone from reading out the program through the bootloader, you need to remove the bootloader. Programming is then done just like you are setting the fuses: Through ISP (for example via a second Arduino).

You didn't include details on the handshake. An important attack route would be to just sniff on the Arduinos Serial interface. Unless your handshake itself is encrypted locking the Arduino will not prevent attackers from getting it.
There are encryption libraries for Arduino (like this one on github). Based on your thread model and the needed resources (since the Uno is rather constrained especially in RAM) you can choose a fitting library and a fitting encryption algorithm. One important attack route would be a replay attack, where the attacker just resends the serial data, that he recorded in the last successfull transmission. One way to prevent that would be a rolling code (like modern garage door openers often use). Or you can create One-Time-Passwords (for example by combining the handshake secret with a timestamp and encrypting/hashing that; you need synchronized time for that).

Handshake works by sending 4 ints hardcoded in .exe. Those 4 ints are hardcoded on arduino, it connects if they match. Before sending i do some basic math operations and reverse them on arduino. Then i send multiple random numbers, do some math ℅ 6 = inc. One byte is one command so i increment command bytes on both sides by inc. Every time arduino connects command bytes are different. If attacker was only sniffing data, he would get random numbers and would need to find a pattern and reverse enginner math operations.

@gagicf2 That is better than transmitting the plain secret, though not impossible to reverse engineer the pattern. I think with a number of sniffed transmissions one could do a statistical analysis and guess the pattern. Though - as stated - it comes down to your thread model. You can decide, that this level of security is enough.

Instead of sending the secret (even obscured) generate a random nonce and send that instead. The Arduino hashes a stored secret concatenated to the incoming nonce, and returns that hash to the computer, which performs the same steps itself (the EXE knows the secret), and compares the two hashes to validate. In this role, you can even use something cryptographically weak but CPU cheap like sha1 or even md5, as long as your nonce is longer than 16 chars, or 24, or 32, whatever you need to sleep. Tiny stand-alone hash functions fit better into MCUs than a whole lib of crypto tools you don't need.


text:
What resistor should I use when using a photo-resistor?
So I'm trying to use a photo-resistor and I learned that you should have a "fixed" resistor in the circuit. So my question is, what resistor should I have be the fixed resistor? My photo-resistor has a resistance of 18-50 KΩ at 10lux and a darkness resistance of 2.0 MΩ at 0lux.

please include the circuit diagram ... what are you trying to accomplish?

What voltage swing to you want. What are you connecting the output to. Post a schematic along with links to technical information on the parts you are using.

What part of the “light curve” are you interested in and what will you be connecting the LDR output / voltage divider to? An LDR that has a resistance of, say, 20k Ohms at 10 lux (which is a very low “candlelight” light level) can have a resistance of only 100 Ohms in daylight (10.000 lux or more). Your voltage divider (input to an ADC i presume?) should be matched with the values you are interested in.

@StarCat does the resistance of the fixed resistor change what kind of values I'll get? Also, what is a "light curve"? And btw I connected the output to the 5V pin on the Arduino.

What part of the “light curve” are you interested in and what will you be connecting the LDR output / voltage divider to?
A photoresistor (LDR) that has a resistance of, say, 20k Ohms at 10 lux (which is a very low “candlelight” light level*) can have a resistance of only 100 Ohms in daylight (10.000 lux or more). Your voltage divider (input to an ADC i presume?) should be matched with the values you are interested in.
That said, if I make the assumption that you want to distinguish between daylight and darkness and you want to connect the LDR voltage divider to an ADC input on your Arduino that has the same range as your power supply (usually 5V or 3.3V), you could build the following voltage divider using your LDR and a 10k Ohm resistor (R1, your "fixed" resistor):

simulate this circuit – Schematic created using CircuitLab
This will give you a fairly wide range of values (with higher values being brighter) and allows you (by experiment) to determine when it's time to turn the lights on, for example.
*Actually, the definition of 1 lux is the amount of light one candle generates at a meter distance, so 10 lux is the light of 10 candles.

Change R1 to a (trim)potentiometer so you can adjust it to your needs.

fun trick: put LDR from ADC to GND, then take the other lead to a GPIO set to "INPUT_PULLUP". Depending on the type of ldr, this can give you full range or sometimes just about 1/4 range, but often that's good enough to tell "it's dark"...


text:
Arduino IDE 1.8.15 won't open
I was using Arduino IDE 1.8.13 but didn't open for a few week and now I can't launch the IDE and any of the sketch. I uninstall it and downloaded the latest version 1.8.15 but it still poses the same problem. Only the initializing window appear and after it disappear, the IDE won't go any further. I run the debug.exe and still the same problem. Anyone has same problem and has the solutions?

run arduino_debug.exe from command line to see the log

Delete your preferences.txt file

@Majenko That works very well. I see other suggestion to remove the json files. but never the preferences file. Thanks alot