texts:
Apparently, this combination of hardware won't accept anything other than WiFiEsp.h together with SoftwareSerial.h (if anyone knows something better/newer than these two, please let me know).
Thing is: I can connect to wifi, send and receive data (to an apache server inside my home network) just fine. After my project was almost done, I decided to connect it to a real server on the internet only to discover that ESP-01 couldn't detect my gateway.

#include "WiFiEsp.h"
#include "SoftwareSerial.h"

int pinWifiRX = 6;
int pinWifiTX = 7;

char ssid[64]    = "*****";
char pass[32]    = "************";

SoftwareSerial Serial1(pinWifiRX, pinWifiTX);

int wifi_status;

void setup() {

  Serial.begin(9600);

  Serial1.begin(9600);
  while(!Serial1) (true);

  WiFi.init(&Serial1);

  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println(F("No shield"));
    while (true) {}
  }

  IPAddress localIp(192, 168, 1, 60);
  IPAddress subnetMask(255, 255, 255, 0);
  IPAddress gateway(192, 168, 1, 36);

  WiFi.config(localIp);  // <--- this line is accepted and works, but the other 3 gives compilation errors
//  WiFi.config(localIp, gateway);
//  WiFi.config(localIp, gateway, subnetMask);
//  WiFi.config(localIp, gateway, subnetMask, gateway);

  wifi_status = WiFi.begin(ssid, pass);

  if (wifi_status == WL_CONNECTED) {

    IPAddress ip;

    ip = WiFi.localIP();
    Serial.print(F("[WiFiEsp] IP Address: "));
    Serial.println(ip);

    ip = WiFi.subnetMask();
    Serial.print(F("[WiFiEsp] Subnet Mask: "));
    Serial.println(ip);

    ip = WiFi.gatewayIP();
    Serial.print(F("[WiFiEsp] Gateway: "));
    Serial.println(ip);

//    ip = WiFi.getDNS();  // <--- function doesn't exist
  }

}

void loop() {}

Results in:

[WiFiEsp] Initializing ESP module
[WiFiEsp] Initilization successful - 2.2.1
[WiFiEsp] IP address set 192.168.1.60
[WiFiEsp] Connected to *****
[WiFiEsp] IP Address: 192.168.1.60
[WiFiEsp] Subnet Mask: 255.255.255.0
[WiFiEsp] Gateway: 192.168.1.0

As one can see, Subnet Mask is corret, but it "detects" Geteway 192.168.1.0 when it should be 192.168.1.36. This way, I can connect to any device in LAN, but cannot access any address on the internet.

I even tried to send some AT commands directly to SoftwareSerial.h, but I don't get any response.

Will I have to start the whole project over from scratch (using another hardware combination), or is there a way to change gateway by hand? Better yet, is there a way to make it detect the gateway's address correctly?

EDIT: could it be related to the firmware I installed to the ESP-01? I followed this tutorial and got it from this link.

Thanks in advance.

EDIT: in this example, i used the WiFi.config(localIp) function to set a fix IP. I don't really need that, it was just an attempt to make it get the correct Gateway address. Even if I comment that line, the Gateway is still wrong.


texts: Methods to prevent Accelerometer values changing from current spikes

texts:
I've connected an Arduino Uno to a MAX7219 IC, which is connected to only one standard 8x8 LED matrix, and an ADXL355 3-axis accelerometer. I use the matrix initially, and turn on all LEDs, while taking the "rest" values for the accelerometer to base all other calculations on. However, what happens is the current spike the LEDs create messes up the values - they become closer to 300, instead of the 230 they settle on when the spike is over. I've tried preventing this by adding up to a 5-second delay between the LEDs turning on and the rest values being measured. However, the problem still persists, though to a somewhat lesser extent.

Are there any methods to prevent this more effectively?


texts: Problem regarding getting split data of JSON - Another issue

texts:
In my recent project, I'm working with Arduino and JSON. I've successfully split the JSON data I want. My JSON data length is fixed. So, I used the length() function and I'm getting the length of my data.

Now, my input JSON data is:

{"TPS":"0.40","MAP":"0.95","LOAD":"14"}

Using the length() function, its length is 39.

But when I use an if statement like if(len == 39) and put my logic inside this, I'm not getting the split data. Below is my whole code.

Here, I'm displaying my data on LCD.

#include<LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 7, 6, 5, 4);
String data_TPS_Json = "";
String data_MAP_Json = "";
String data_LOAD_TM_Json = "";
String response = "";
bool begin = false;
int counter = 0;
int len = 0;
char in;
float TPS_Json;
float MAP_Json;
float LOAD_TM_Json;

void setup() {
  Serial.begin(9600);
  lcd.begin(16, 2);
}

void loop() {
  while(Serial.available() || !begin) {
    in = Serial.read();
    if (in == '{') {
      begin = true;
    }
    if(begin) {
      counter++;
      response += (in);
      len = response.length();
      if(len == 39) {
        if(counter >= 9 && counter <= 12) {
          data_TPS_Json += (in);
        }
        if(counter >= 22 && counter <= 25) {
          data_MAP_Json += (in);
        }
        if(counter >= 36 && counter <= 37) {
          data_LOAD_TM_Json += (in);
        }
      }
    }

    if(in == '}') {
      break;
    }
    delay(1);
  }
  TPS_Json = data_TPS_Json.toFloat();
  MAP_Json = data_MAP_Json.toFloat();
  LOAD_TM_Json = data_LOAD_TM_Json.toFloat();
  lcd.setCursor(0, 0);
  lcd.print(TPS_Json);
  lcd.setCursor(8, 0);
  lcd.print(MAP_Json);
  lcd.setCursor(0, 1);
  lcd.print(LOAD_TM_Json);
}


texts: How do I download a sketch to an Arduino semi-permanently?

texts:
I will be working with Arduino(s), and I would like to find a way to download the sketches to the board semi permanently, in a way that I can remove the USB from the board, apply power, and still have the Arduino execute the code

I am planning to use Mega2960, Uno, and Nano. If there are any differences between the uploading process,
please let me know.

P.S., I am using boards produced by Elegoo, not by Arduino, if that makes a difference.


texts: How to delegate code compilation to a remote machine?

texts:
Sometime I write Arduino code on a slow Windows laptop that I use for controlling hardware projects and 3D printing.

My main Windows computer and also my Linux home server are located somewhere else but are much faster and I would like to use those for compilation.

Remote Desktop or equivalent are not practical due to different screen resolutions. Also, my main Windows machine is not always on, only the server is, but it has no GUI installed.

The sources are already located on a shared network folder and I use an external editor for the code. Arduino IDE just does compilation and sometimes upload (which often I could do via OTA).

How to delegate compilation of Arduino projects to a remote machine?


texts: ATmega328P of Arduino Pro Mini not responding

texts:
While I was trying to change the fuse bits of ATmega328P of my Arduino pro mini using a USBasp device to operate it at 3.3 V/8 MHz, it failed due to the bad connection I guess. After that, the USBasp programmer can't detect the chip.

Does the MCU get bricked/locked?

How can I recover this?

Is there any way to solve this problem using an AVR Dragon board? If yes, please let me know the whole process.


texts: How to connect ESP8266-01 (AT-commands) to its web server using AJAX

texts:
I am just new on using AJAX in web server, I got an error on declaring "server" I am confused about this because I just used only a AT commands to used the ESP8266-01 (wifi-module) I hope you can help me, I want to get the data (distance) to print in the web server(page) in real-time(no refresh). So I used the AJAX for it but this code is still error. Advance thanks on anyhelp :)

 #include "NewPing.h"
 #include <SoftwareSerial.h>
 #define DEBUG true

 SoftwareSerial esp8266(10,11);
 #define TRIGGER_PIN 4
 #define ECHO_PIN 3
 #define MAX_DISTANCE 400

 NewPing sonar(TRIGGER_PIN,ECHO_PIN,MAX_DISTANCE);

 void setup() {
 Serial.begin (9600);
 Serial.println("START");
 esp8266.begin(9600);

 server.on("/",WebsiteContent);
 server.on("/xml",XMLcontent);
 server.begin();

 pinMode(TRIGGER_PIN, OUTPUT);
 pinMode(ECHO_PIN, INPUT);

 sendData("AT+RST\r\n",2000,DEBUG);
 sendData("AT+CWMODE=2\r\n",1000,DEBUG);
 sendData("AT+CIFSR\r\n",1000,DEBUG);
 sendData("AT+CIPMUX=1\r\n",1000,DEBUG);
 sendData("AT+CIPSERVER=1,80\r\n",1000,DEBUG);

}

void javascriptContent(){
Javascript ="\n";

}
void WebsiteContent(){
javascriptContent();

 Website="\n";
 Website+="\n";
 Website+="";
 Website+="
"+data+"
";
 Website+=Javascript;
 server.send(200,"text/html",Website);
 }
 void XMLcontent(){

 XML ="<?xml version='1.0'?>";
 XML+="<data>";
 XML+=data;
 XML+="</data>";

 server.send(200,"text/xml",XML);

 }
 void loop()
 {

 delay(2000);
 digitalWrite(TRIGGER_PIN, LOW);
 delayMicroseconds(2);
 digitalWrite(TRIGGER_PIN, HIGH);
 delayMicroseconds(10);
 digitalWrite(TRIGGER_PIN, LOW);

 long duration,distance;
 duration= pulseIn(ECHO_PIN,HIGH);

 distance = duration/58.2;

 data=(String)distance;
 delay(500);

 server.handleClient();

 if(esp8266.available())
 {
 if(esp8266.find("+IPD,"))
 {
 delay(1000);
 int connectionId = esp8266.read()-48;

 String cipSend = "AT+CIPSEND=";
 cipSend += connectionId;
 cipSend += ",";
 cipSend +=webpage.length();
 cipSend +="\r\n";
 sendData(cipSend,1000,DEBUG);
 sendData(webpage,1000,DEBUG);
 String closeCommand = "AT+CIPCLOSE=";
 closeCommand+=connectionId;
 closeCommand+="\r\n";
 sendData(closeCommand,3000,DEBUG);

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


texts:
I've bought an HC-SR501-compliant PIR motion sensor (like this one) and connected it to a Teensy 3.1. The circuit seems fine, and the LED lights up. However, when nothing is moving in front of it, the sensor keeps reporting HIGH and LOW in suspiciously constant intervals. The monitor reads like this (numbers in milliseconds)

motion detected  4113
motion stopped   7234
motion detected  4114
motion stopped   7274
motion detected  4113
motion stopped   7204
motion detected  4111
motion stopped   7184

When it detects movement, it stays on the triggered position for longer, but even then goes back to predetermined intervals, e.g.

motion detected   4113
motion stopped   17204
motion detected   4111
motion stopped   41754
motion detected   4113

This is the sketch (as found on Adafruit):

int ledPin   = 13;              // choose the pin for the LED
int inputPin = 1;               // choose the input pin (for PIR sensor)
int pirState = LOW;             // we start, assuming no motion detected
int val      = 0;               // variable for reading the pin status

unsigned long lastTime = millis();

void setup() {
  pinMode(ledPin, OUTPUT);      // declare LED as output
  pinMode(inputPin, INPUT);     // declare sensor as input

  Serial.begin(9600);
}

void loop(){
  unsigned long currentTime = millis();

  val = digitalRead(inputPin);   // read input value
  if (val == HIGH) {             // check if the input is HIGH
    digitalWrite(ledPin, HIGH);  // turn LED ON
    if (pirState == LOW) {

      // we have just turned on
      Serial.print("motion detected ");
      Serial.println(currentTime - lastTime);

      // We only want to print on the output change, not state
      pirState = HIGH;

      // Save time for measurement
      lastTime = currentTime;
    }
  } else {
    digitalWrite(ledPin, LOW); // turn LED OFF
    if (pirState == HIGH){

      // we have just turned off
      Serial.print("motion stopped ");
      Serial.println(currentTime - lastTime);

      // We only want to print on the output change, not state
      pirState = LOW;

      // Save time for measurement
      lastTime = currentTime;
    }
  }
}

Could this be a faulty device? I'm thinking about getting a new one for testing. While I can compensate for the gaps when triggered, I can't think of a way to make sure that it's not actually being triggered by this weird internal interval.


texts: How to use more than 2 I2S microphones on MKR Zero?

texts: I am trying to build a portable device that can record from at least 3 microphones. I had a look and saw I2S is good for audio so I bought an Arduino MKR Zero to read them with. I was wondering how to record from multiple microphones on the I2S bus at once. The only thing that I have been able to do is record stereo from two mics but I need the microphone readings to be mono. I am using the Adafruit I2S MEMS Microphone SPH0645LM4H.


texts: ADXL345 becomes 0g when plugin MicroSD Adapter using SPI

texts:
Try SD SPI code and ADXL345 SPI code separately and both are fine. When merge the codes, ADXL345 reading okay (not plug in MicroSD Adapter). Pin should bo okay.

Every time MicroSD is plugged (the same pin working with above code), ADXL345 reading suddenly becomes 0g, 0g, 0g. Pull it out then reading is good.

See https://forum.arduino.cc/index.php?topic=360718.0 and not sure if this is due to a hardware defect on MicroSD Adapter.

Already read many post like https://forum.sparkfun.com/viewtopic.php?f=14&t=38072 and the code produce 0g result, too.

Is it purely a hardware problem? Anyone suggest another one?
Is there any way to fix in software?

More details: I am using Nodemcu v1. and arduino library. The connected pins for SD and ADXL345 both at HSPI pins. I understand Nodemcu has another SPI (or even for SD card (SD0, SD1, ...etc), but I did not see any example by using those two and integrate with ADXL345 on HSPI.


texts:
I want to write my data on google sheets using ESP 01 and Arduino Nano.
So I copied code from some website I don't remember the website "how to send data on a local server" and modified it a bit.
But it is directly sending the data to the local server only.

Please help me to call Pushing box API and write on Google Sheets.

Here is my current code:

#include<SoftwareSerial.h>

SoftwareSerial comm(12,11); //setting Tx and Rx pins

String server=""; //variable for sending data to webpage
boolean No_IP=false; //variable to check for ip Address
String IP=""; //variable to store ip Address
char temp1='0';

int a=0;
int b=0;

void setup()
{
Serial.begin(9600);
comm.begin(9600);
wifi_init();
Serial.println("System Ready..");
}

void loop()
{
b=0;
Serial.println("Refresh Page");
while(b<1000)
{
b++;
while(comm.available())
{
if(comm.find("0,CONNECT"))
{
Serial.println("Starting");
sendToServer();
Serial.println("Finished");
delay(1000);
}
}
delay(1);
}
}

void findIp(int time1) //check for the availability of IP Address
{
int time2=millis();
while(time2+time1>millis())
{
while(comm.available()>0)
{
if(comm.find("IP has been read"))
{
No_IP=true;
}
}
}
}

void showIP()//Display the IP Address
{
IP="";
char ch=0;
while(1)
{
comm.println("AT+CIFSR");
while(comm.available()>0)
{
if(comm.find("STAIP,"))
{
delay(1000);
Serial.print("IP Address:");
while(comm.available()>0)
{
ch=comm.read();
if(ch=='+')
break;
IP+=ch;
}
}
if(ch=='+')
break;
}
if(ch=='+')
break;
delay(1000);
}
Serial.print(IP);
Serial.print("Port:");
Serial.println(80);
}

void establishConnection(String command, int timeOut) //Define the process for sending AT commands to module
{
int q=0;
while(1)
{
Serial.println(command);
comm.println(command);
while(comm.available())
{
if(comm.find("OK"))
q=8;
}
delay(timeOut);
if(q>5)
break;
q++;
}
if(q==8)
Serial.println("OK");
else
Serial.println("Error");
}

void wifi_init() //send AT commands to module
{
establishConnection("AT",100);
delay(1000);
establishConnection("AT+CWMODE=3",100);
delay(1000);
establishConnection("AT+CWQAP",100);
delay(1000);
establishConnection("AT+RST",5000);
delay(1000);

Serial.println("Connecting Wifi....");
establishConnection("AT+CWJAP=\"Leobotics\",\"leobotics123\"",7000); //provide your WiFi username and password here
delay(2000);
Serial.println("Wifi Connected");
showIP();
establishConnection("AT+CIPMUX=1",100);
establishConnection("AT+CIPSERVER=1,80",100);
}

void sendData(String server1)//send data to module
{
int p=0;
while(1)
{
unsigned int l=server1.length();
Serial.print("AT+CIPSEND=0,");
comm.print("AT+CIPSEND=0,");
Serial.println(l+2);
comm.println(l+2);
delay(100);
Serial.println(server1);
comm.println(server1);
}
}
void sendToServer()//send data to webpage
{
//String aquib = "http://busgetbeast.in";
sendData("http://api.pushingbox.com/pushingbox?devid=vBDFF4154ABE4F6F&humidityData=33&celData=44&fehrData=111&hicData=22&hifData=77");
      sendData(" HTTP/1.1");
      sendData("Host: ");
      sendData("api.pushingbox.com");
      sendData("User-Agent: ESP8266/1.0");
      sendData("Connection: close");
    // sendData();
delay(5000);
comm.println("AT+CIPCLOSE=0");
}


texts:
I know it is not a good practice to use the new command to dynamically create data, however, if I would never use the delete, would it result in memory gaps/other problems?

Background

The reason I need to create instances dynamically, is that I want to test my application first on a PC. And I want for several classes to have more properties for the PC version than for the Arduino version (for example, to store names, or information for the PC GUI to display). The PC version classes will be inherited from the Arduino (real) classes, but with added properties.

In some classes I need to build up a list, and I cannot use a type with hardcoded values to fill an array.

Example:

I have a LightSetup class that has a list of Pars (which are LED lights):

class LightSetup
{
protected:
    Par* _pars[NR_OF_PARS];

Par is the Arduino/real version, to fill in these I need:

LightSetup::LightSetup()
{
    for (int n = 0; n < NR_OF_PARS; n++)
    {
        _pars[n] = new Par(1 + 8 * n);
    }
}

In the PC version, instead of new Par, I use new TestPar.
And in the header I cannot define it without a pointer like this:

    Par _pars[NR_OF_PARS];

Otherwise it cannot contain TestPar instances.


texts:
Alright, so this code is for a game that is a power source connected to 6 buttons at ports 1, 2, 9, 11, 12, and 13. These are consequently supposed to light up 6 LEDs, each connected to 1. If you press the buttons in the right order, all the LEDs blink at once. Does it work?

int ledPin1 = 1;
int ledPin2 = 2;
int ledPin3 = 9;
int ledPin4 = 11;
int ledPin5 = 12;
int ledPin6 = 13;

void setup() {
//put your setup code here, to run once:
}
void loop() {
//put your main code here, to run repeatedly:
int QuestionNumberArray[] = {1, 2, 9, 11, 12, 13};//the array itself
const size_t n = sizeof(questionNumberArray) //the array used
sizeof(questionNumberArray[0]);//the base of the array

for (size_t i = 0; i < n - 1; i++) //the loop itself
{
size_t j = random(1, n-i);
int t = questionNumberArray[i]; //integer output for increase
questionNumberArray[i] = questionNumberArray[j];//the value definition
questionNumberArray[j] = t;
pinMode(questionNumberArray, INPUT);
if(digitalRead(questionNumberArray) == HIGH) {
then(digitalRead(1, 2, 9, 11, 12, 13) == HIGH)
break;
}
}

Also, how do I make it so that people have multiple tries to do it, or is it already like that?
Thank you


texts: not getting proper bitstream output in serial monitor using digitalRead

texts: I am producing a  data stream and feeding to a gpio pin. THe data is sampled at 2kbps. i want to dump this data into a file after a certain length of reading . how should i proceed with this ?


texts:
I am doing a project, and I need an SD card. Everything worked well, but after a while when I read the SD card from my PC(Windows 10 64 bit, Intel Core), I found a file called eecfbba=.@aa. It's so big that it almost ate up one GB storage of my SD card. But when I tried to open it with notepad, notepad tells me that there is actually no such file, and asks me if I want to create it. I tried to delete it, but file explorer also told me there is no such file. What is it?

This is my code:

#include <ArduinoJson.h>

// Version 0.20.1.19.3.7:
// 2020/01/19, 16:10, button record test, 7th version.

#include <SD.h>
#include <SPI.h>
#include <TMRpcm.h>
#include <Wire.h>
#include "RTClib.h"
//#include <string.h>

RTC_DS1307 rtc;
String strdoc;
char daysOfTheWeek[7][2] = {"su", "mo", "tu", "we", "th", "fr", "sa"};
#define SD_ChipSelectPin 10  // 如果使用 arduino nano 328 可使用Pin4

TMRpcm audio;
void setup() {
  audio.speakerPin = 8;
  Serial.begin(9600);
  pinMode(25, INPUT_PULLUP);
  pinMode(7, INPUT_PULLUP);
  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }
  if (! rtc.isrunning()) {
    Serial.println("RTC is NOT running!");
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  }
  else
  {
    Serial.println("rtc started");
  }

  if (!SD.begin(SD_ChipSelectPin)) {
    Serial.println("SD Fail");
    return;
  } else {
    Serial.println("SD OK");
  }

  audio.setVolume(6);
  audio.CSPin = SD_ChipSelectPin;

  StaticJsonDocument<200> doc;
  doc["sensor"] = "gps";
  doc["time"] = 1351824120;
  JsonArray data = doc.createNestedArray("data");
  data.add(48.756080);
  data.add(2.302038);
  serializeJson(doc, strdoc);
}
bool isrecording = false;
bool recordButtonPressed()
{
  return (digitalRead(25) == LOW);
}
bool playButtonPressed()
{
  return (digitalRead(7) == LOW);
}
void loop() {
  delay(200);
  // Below is the formatted datetime.
  DateTime now = rtc.now();
  // Below is the serialized datetime.
  String filename = (String)(now.unixtime() % 10000000) + ".j";
  //  Serial.println(filename);
  if (recordButtonPressed())
    if (!isrecording)
    {
      isrecording = true;
      audio.startRecording("test.wav", 16000, A0);
      Serial.println("stt");
    }
    else
    {
      isrecording = false;
      Serial.println("stp");
      audio.stopRecording("test.wav");
    }
  Serial.println("sdsad991===`=`");
  if (playButtonPressed())
  {
    audio.play("test.wav");
    Serial.println("ply");
  }
  String dataString = strdoc;
  if (!isrecording)
  {
    File dataFile = SD.open(filename, FILE_WRITE);

    if (!dataFile) {
      Serial.println(F("Failed to create file"));
    }
    else
    {
      dataFile.println(dataString);
      Serial.println("Wrote string.");
      dataFile.close();
      Serial.println("Closed file.");
    }
  }
  /* Please ignore this line */
  //  //    audio.play("test.wav"); break;audio.volume(1); break;audio.volume(0); break;audio.stopPlayback(); break;
}

P.S. I'm using Mega 2560, so MISO, MOSI, SCK and CS pins are different.(Which is 50,51,52,10).

Edit 2020/1/25, 14:15(Beijing Time) At 1/20 I have bigger problems. There are more and more big files. All of them are the same situation. For details, take a look at this photo(ignore selected files): Imgur or 咱们中国人上不去imgur，用这个：File-up（直接下载）


texts:
I understand that A-B plug used to be common but they could have switched to micro without issues.

My questions:

Why does Arduino use USB A-B plug, instead of A to micro USB plug?
What are the challenged Arduino would be facing if they switched to micro USB?

Note:
By "Arduino" I'm referring to Arduino models that do not come with a micro USB port such as the most common Uno & Mega.


texts:
I have a project which has two options
No. 1 Randomly turn on one LED from a group of 6 LED (Relay Board)
No.2 randomly turn on one LED from a group of 2 LED (Relay Board)
The selection of the desired option happens with a switch.

I found this code online which is just perfect for 6 LED but I don't know how to add the selection of the options in it, how to do it?

int timeShowRandom = 3000;
int timeShowDecision = 6000;
int timeBlink = 100;
int buttonPin = 2;
int buttonPress = false;
int randomNumber;
int previousNo = 0;
int timePassed = 0;

void setup() {
  // Set button pin
  pinMode(buttonPin, INPUT);
  // Set output pins
  pinMode(12, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(7, OUTPUT);
}

void getRandomNo() {
 int rand = random(7,13);
  if (rand == previousNo) {
   getRandomNo();
  } else {
    randomNumber = rand;
    previousNo = randomNumber;
  }
}

void loop() {
 if (digitalRead(buttonPin) == HIGH && buttonPress == false ) {
     buttonPress = true;
  } if (buttonPress == true && timePassed <= timeShowRandom) {
    getRandomNo(); // Get random pin number
    digitalWrite(randomNumber, LOW);
    delay(timeBlink);
    digitalWrite(randomNumber, HIGH);
    delay(timeBlink);
   timePassed = timePassed + (timeBlink * 2);
  } else if(buttonPress == true) {
    digitalWrite(random(7,13), LOW); // Set random pin on
    delay(timeShowDecision); // For x seconds
    buttonPress = false; // Set button to be enabled again
    timePassed = 0;
  }
  else {
    // Reset all output pins
    digitalWrite(10, HIGH);
    digitalWrite(11, HIGH);
    digitalWrite(12, HIGH);
    digitalWrite(9, HIGH);
    digitalWrite(8, HIGH);
    digitalWrite(7, HIGH);
  }
}


texts: Powering an Arduino Mega with external USB Power Bank?

texts: I am making a robot with arduino mega r3. I want to power the arduino with a usb power bank. How should I do that?


texts: STM32 and SDFat - Can't create file in directory in SD

texts:
I'm using the SdFat.h library on a STM32 and I can successfully create a file in the root directory using SD.open("test.txt", FILE_WRITE); but my code fails to create SD.open("DATA/data_test.txt", FILE_WRITE); in a directory.
Here's the piece of code that successfully creates a file in the root:

String final_book_name = upload_book_name + ".txt";
if (SD.exists(final_book_name.c_str())) {
  SD.remove(final_book_name.c_str());
}
tft.println(final_book_name); // This successfully prints "test.txt"
book_file = SD.open(final_book_name, FILE_WRITE);
if (SD.exists(final_book_name.c_str())) {
  tft.print("Created file");
} else {
  tft.print("Failed to create/replace\nfile!");
}

and here's the piece of the code that fails to create a file in a directory:

if (!SD.exists(DATA_DIR)) {
  SD.mkdir(DATA_DIR);
}
String final_book_name = upload_book_name + ".txt";
String book_data_path = DATA_DIR;
book_data_path += "/data_" + final_book_name;
if (SD.exists(book_data_path.c_str())) {
  SD.remove(book_data_path.c_str());
}
tft.println(book_data_path); // This successfully prints "DATA/data_test.txt"
File book_data_file = SD.open(book_data_path, FILE_WRITE);
if (SD.exists(book_data_path.c_str())) {
  book_data_file.print(upload_book_font);
  book_data_file.print("|");
  book_data_file.print("0");
  book_data_file.close();
} else{
  tft.print("Failed to create/replace\ndata file!");
  if (SD.exists(final_book_name.c_str())) {
    SD.remove(final_book_name.c_str());
  }
}


texts:
I'm searching for a way to flash an esp8266 programmatically, i.e, without user interaction (and especially without Arduino IDE)?
Assuming I can put the program to be flashed on the SPIFFS filesystem, is there a way to flash the esp with that file?


texts: Is it possible to use LCD (the 16 pins) without potentiometer?

texts:
look, I don't have any potentiometer lying around, and I don't have any variable resistor.
So is it possible to instead use a fixed resistor for the LCD display ?


texts: How can I make the Serial Monitor work with the Serial Commands library?

texts:
I am using the library SerialCommands and I am just trying to print the first text message in the Serial Monitor. But this code does not work for some reason.

The expected result is that the Serial monitor prints a message ("Hello world !!") when I write "hello" and press "enter" as input. Is there something wrong or is this not working like I was expecting? Is there another way to check if these commands work? Is there anythin that I am missing?

#include <SerialCommands.h>

char serial_command_buffer_[32];
SerialCommands serial_commands_(&Serial, serial_command_buffer_, sizeof(serial_command_buffer_), "\r\n", ",");

void cmd_hello(SerialCommands* sender) {
  sender->GetSerial()->println("Hello world !!");
}

SerialCommand cmd_hello_("hello", cmd_hello);

void cmd_unrecognized(SerialCommands* sender, const char* cmd) {
  sender->GetSerial()->print("ERROR: Unrecognized command [");
  sender->GetSerial()->print(cmd);
  sender->GetSerial()->println("]");
}

void setup() {
  Serial.begin(9600); // Serial comm begin at 9600bps
  serial_commands_.AddCommand(&cmd_hello_);
  serial_commands_.SetDefaultHandler(&cmd_unrecognized);
  Serial.println("Ready");
}

void loop() {
  serial_commands_.ReadSerial();
}


texts: Why am I only seeing 1.3V on an analog pin that has been set to high using digitalWrite?

texts:
I have run into a bit of trouble with a sewable electronics project. I am trying to power a SparkFun 7-Segment Serial Display from one of the analog ports of a ATmega328 board. I realize this is unconventional, but I designed the circuit to not require any crossed connections to make the sewing a bit easier, and that was the only way to do it. The display wouldn't light up, and after some debugging with a multi-meter it turned out that the analog pin I was using (A3) was only at 1.3V despite a digitalWrite command. I tested the same command on one of the other analog pins (A0) and it produced 5V as expeced. When I bridge the VCC pin and A3, everything works fine. When I set A0 to 5V , and bridge it with A3, the output voltage drops to 1.8V relative to GND.

The really weird thing is that just running the example code from the sparkfun website without any modifications still somehow results in a \~1.2V reading from A3 to GND. I have no clue what is going on here. Usually I would disconnect the display from A3 and keep testing, but I am trying to avoid it. Troubleshooting is difficult as I had to clip the excess tails to prevent short circuits making me extremely reluctant to disconnect anything until I have figured out what the problem is, as the thread is very hard to work with, and it took the project on the order of 60 man-hours to get where it is. I was hoping someone here might know what is going on, or point me in the right direction.


texts:
Suppose that one defined a data structure and wanted to send it through serial.

 struct Gyro_data_structure {
    char command_name[5];
    float gyro_X;
    float gyro_Y;
    float gyro_Z;
};

Gyro_data_structure Gyro_data;

int size_gyro=sizeof(struct Gyro_data_structure);

void setup() {
  Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
}

void loop() {
  Gyro_data.command_name[0]='H';
  Gyro_data.gyro_X++;
  Serial.println(size_gyro);
  delay(500);
  Serial.write(Gyro_data,size_gyro);
}

However, it returned an error saying "no matching function for call to 'HardwareSerial:write(Gyro_data_structure&,int&)'". I googled and found Michaël Roy's answer here. However, it's not working: "can not convert ..."

How to send a structure through UART?


texts: about how to share one External serial EEprom using two microcontrollers?

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

{

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

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

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

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

}


texts: Where to find the attribution name for a certain board?

texts:
I'm working on lcd128x64 spi library. And was working with my Arduino Atmega328p chip.

Now I want to run the code with my maple mini board too.
So I have to specify the name on the pins for each chip board.
But I want to learn the basics of how to write these statements.

Could you tell me where to find the attributions for each board ?

For now I want to define the pin names for the Atmega328p and maple mini. This is my intention:

#if defined(__AVR_ATmega328P__)
    #define CS_PIN                  10
    #define MOSI_PIN                11
    #define CLK_PIN                 13
#elif defined(STM32_SERIES_F1)
    #define CS_PIN                  PB12
    #define MOSI_PIN                PB15
    #define CLK_PIN                 PB13
#endif

I don't think that's %100 correct, but I'm pretty sure that it's not the correct names of boards.


texts: Arduino Uno Port access denied error, and probably other issues

texts:
I am trying to write a script to measure the voltage in an Arduino pin, convert that to a corresponding temperature measurement, end export the serial data to a csv file.
I know there is probably a lot more wrong with this code, but the problem I have right now is that I am getting this error:
could not open port 'COM6': PermissionError(13, 'Access is denied.', None, 5)
I have tried closing other programs that might occupy it, and I have tried running the IDE as an administrator, and I have tried changing ports. but now I am at a loss....
    import numpy as np
import serial
import pyfirmata
import time  #Required to use delay functions
import csv

portName = 'COM7'
arduino = pyfirmata.Arduino(portName)
cnd = False
it = pyfirmata.util.Iterator(arduino)
it.start()
ser=serial.Serial(portName)
ser.flushInput()
print(1)
while True:
    try:
        #Connect to arduino hardware on input port.
        input_pin = arduino.get_pin('a:0:i') #analog, input to the computer
        output_pin = arduino.get_pin('d:3:o') #digital, output from the computer
        output_pin.mode = 3  #PWM mode
        # Set the output of digital pin 3 to high (5V), this will heat R2
        output_pin.write(1) #writes to D3
        time.sleep(5)
        #set the output of digital pin 3 to low (0V)
        output_pin.write(0)
        cnd = True

    except:
        print('Can not connect. \n')

    if cnd:
        try:
            signal0 = input_pin.read()
            #print(signal0 ,' V.')
            R4=signal0*15000/(5-signal0)
            #print(R4,' ohm.')
            temp=-np.log(R4/70498)/0.025
            #print("the temperature is ",temp," F")
            with open("test_data.csv","a")as f:
                writer=csv.writer(f,delimiter=",")
                wrier.writerow([time.time(),temp])

        except:
            print("keyboard interupt")
            break

wait = input("Press Enter to Continue")


texts: How to properly use interruptions with twi (I2C)

texts:
I would like to reprogram Wire.h, or a part, to use interruptions, in order to not waste time to wait. I'm using an Arduino Mega with an Adafruit motor shield v2.3.

In the datasheet, page 262, 24.9.2, bit 0, I can read that I have to set the TWIE flag to one to be able to catch the interruption.

So, I started to write this code :

//https://www.arduino.cc/en/uploads/Main/arduino-mega-schematic.pdf

#include <avr/interrupt.h>

#define ADDRSHIELD 0xC0//adresse sur 8 bits

#define TWI_FREQ 100000L
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |=  _BV(bit))

#define START       0x08  //TWI start
#define MT_SLA_ACK  0x18   //slave ACK has been received
#define MT_DATA_ACK 0x28   //master ACK has been received

#define LED0_ON_L 0x6

#define TWI_STATUS      (TWSR & 0xF8)

int etat = 0;
uint8_t currentstep = 0;
uint8_t _addr;
uint8_t _data;

ISR(TWI_vect)
{
  //I remove the TWINT flag
  TWCR |= (1<<TWINT);

  switch(etat)
  {
    case 0:
      //start has been send, let's check if it's ok
      if(TWI_STATUS == START)
      {
        //on charge l'adresse dans TWDR et on clear le bit TWINT dans TWCR pour demarrer la transmission
        TWDR = _addr;
        TWCR = _BV(TWIE) | _BV(TWEN);
        etat = 1;
        //Serial.println(etat);
      }
      else
      {
        etat = -1;
      }
      break;
    //addr has been send
    case 1:
      if(TWI_STATUS == MT_SLA_ACK)
      {
        TWDR = _data;
        TWCR = _BV(TWIE) | _BV(TWEN);
        etat = 2;
        //Serial.println(etat);
      }
      else
      {
        etat = -2;
      }
      break;
    //data have been send
    case 2:
      if(TWI_STATUS == MT_DATA_ACK)
      {
        // disable twi module, acks, and twi interrupt
        TWCR = (1<<TWIE)|(1<<TWEN)|(1<<TWSTO);
        etat = 3;
        //Serial.println(etat);
      }
      else
      {
        etat = -3;
      }
      break;
    //stop condition
    case 3:
      // desactivate internal pullups for twi.
      digitalWrite(SDA, 0);
      digitalWrite(SCL, 0);
      etat = 0;
      //Serial.println(etat);
      //Serial.println("Next");
      break;
  }
}

void sendData(uint8_t addr, uint8_t data)
{
  _addr = addr;
  _data = data;

  i2cSetup();
  //start condition
  TWCR = (1<<TWSTA)|(1<<TWEN)|(1<<TWIE);
}

void i2cSetup(void)
{
  // activate internal pull-ups for twi
  sbi(PORTD, 0);
  sbi(PORTD, 1);

  // initialize twi prescaler and bit rate
  cbi(TWSR, TWPS0);
  cbi(TWSR, TWPS1);

  TWBR = ((F_CPU / 100000) - 16) / 2;
}

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

void loop()
{
  if(etat == 0)
  {
    sendData(0xC0, 0b1010101);
  }
  if(etat == 3)
  {
      Serial.println("Next");
  }
  if(etat == -1)
  {
    Serial.println("Error from start");
    delay(100);
    exit(-1);
  }
  if(etat == -2)
  {
    Serial.println("NACK");
    delay(100);
    exit(-1);
  }
  if(etat == -3)
  {
    Serial.println("DATA NACK");
    delay(100);
    exit(-1);
  }
}

My problem is, once I reset TWIE to one on my interruption, the code looks like to freeze(in ISR(), case 0, TWCR =...). In my mind, the interruption is call only when TWIE is set to one and when the twi module says (when he sets TWINT to one I guess) that he finished the job. I don't understand how to properly use this interruption.

EDIT :
Thanks to @jfpoilpret, know I clearly know the problem, the slave doesn't reply by an acknowledge (in my switch, case 0, the status isn't equal to START (0x08)). In the datasheet, p246, they clearly explain how to use registers, but I'm not sure how to use the flag TWIE. I don't know if I have to set them both to one, or if i have to completely leave TWINT (I tried both, but nothing worked...).

Thanks for your help,
julien


texts: Would it be possible to use to of these on two separate arduino's, to send and receive information? I am having difficulties understanding the chinese-english descriptions and haven't seen any documentation on doing this. There would be no phone involved. There would only be two arduino's with a Bluetooth module on each of them sending and receiving data from each other.


texts:
I am a Beginner in Arduino Programming.
I am working on a project where I control A DC motor with IR sensor and arduino.

Until here it is fine. But I want the Motor to stop after one second even though the IR sensor detects the Obstacle

Here's My Program

Pin 2- IR Sensor
Pin 4,5,6- Motor

enter code here
//Included Libraries
#include <motor.h>

//MACROS are defined here
Motor Motor1(4, 5, 6);

void setup() {
    //put your setup code here, to run once:

    pinMode(2, INPUT);

}

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

    if(digitalRead(2)) {
        Motor1.moveMotor(2.55*0);
    }
    else {
        Motor1.moveMotor(2.55*100);
    }
}

Can anyone help out in this Program. I Just want the Motor to stop after one second.
Thank you in advance!


texts:
I'm having trouble with the syntax of code. I want to have the motor turn when the next average the program measures is 100 or more greater than the previous average it measured. I don't know how to write the if statement:

if(average == (average>=100)) {
for(pos = 0; pos <= 120; pos += 1) {
  sServo.write(pos);
  delay(50);
}
for(pos = 120; pos >= 0; pos -= 1) {
  sServo.write(pos);
  delay(50);
}
}


texts: Help making LEDs blink like blinkers in a car

texts:
I am trying to make blinkers and hazards lights for a car.  I can get
the left and right blinkers to work. I cannot figure out how to get
the lights to blink simultaneously like hazard lights would.

What I think I want is that when both inputs are HIGH then Both LEDs will
blink together at the same time.

I left the garbage and comments in the code so you can see what I have
tried.

Thanks for your help.

/*
 Blinkers and Hazard Lights

 Simulates a vehicles blinkers and Hazard Lights
 left button connected to pin 2 using a pushdown resister
 right button connected to pin 3 using a pushdown resister
 left LED connected to pin 9
 right LED connected to pin 10
 Hazard LED is Pin 13 At one point I was trying to make pin 13 represent the hazard lights but that is not what I want to do.

 When left button is pushed Left LED will Blink
 When Right Button Is pushed Right LED will Blink

 If this worked the way I wanted it to. when both buttons where HIGH both LED 9 & 10 would blink simultaneously.

 created 2015
 by thomsl41@gmail.com

*/

// constants won't change. They're used here to
// set pin numbers:
const int buttonPinLeft = 2;     // the number of the pushbutton pin
const int buttonPinRight = 3;
const int buttonPinHazard = 2 && 3;
const int ledPinLeft = 9;      // the number of the LED pin
const int ledPinRight = 10;
const int ledPinHazard = 13;

// variables will change:
int buttonStateLeft = 0;         // variable for reading the pushbutton status
int buttonStateRight = 0;
int buttonStateHazard = 0;

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPinLeft, OUTPUT);
   pinMode(ledPinRight, OUTPUT);
   pinMode(ledPinHazard, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPinLeft, INPUT);
  pinMode(buttonPinRight, INPUT);
  pinMode(buttonPinHazard, INPUT);
}

void loop(){
  // read the state of the pushbutton value:
  buttonStateLeft = digitalRead(buttonPinLeft);
  buttonStateRight = digitalRead(buttonPinRight);
  buttonStateHazard = digitalRead(buttonPinHazard);

  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonStateLeft == HIGH) {
    // turn LED on:
  digitalWrite(ledPinLeft, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(500);              // wait for a second
  digitalWrite(ledPinLeft, LOW);    // turn the LED off by making the voltage LOW
  delay(500);              // wait for a second
  }
 else {
    // turn LED off:
    digitalWrite(ledPinLeft, LOW);
  }

if (buttonStateRight == HIGH) {
    // turn LED on:
  digitalWrite(ledPinRight, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(500);              // wait for a second
  digitalWrite(ledPinRight, LOW);    // turn the LED off by making the voltage LOW
  delay(500);              // wait for a second

}
  else {
    // turn LED off:
    digitalWrite(ledPinRight, LOW);
  }
}

/*if (buttonStateHazard == HIGH) {
    // turn LED on:
  digitalWrite(ledPinLeft, LOW);
  digitalWrite(ledPinRight, LOW);
  digitalWrite(ledPinHazard, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(2000);              // wait for a second
  digitalWrite(ledPinHazard, LOW);    // turn the LED off by making the voltage LOW
  delay(2000);              // wait for a second
  //}
 //else {
    // turn LED off:
   // digitalWrite(ledPinHazard, LOW);
 }

}
*/


texts: POST to server using ESP8266 module- Arduino Uno- AT+ commands

texts:
I'm trying to send a set of data in Json format to a server I have set up which has a specific URL and an access token. The server requires a POST command. So my final URL is: http://myurl.com/myaccesstoken

The idea is that the Arduino UNO acquires some data from a sensor it then uses the ESP8266 to connect to wifi and send the acquired data to my server.

I do not understand why my server does not receive data

Thank you a lot in advance for your help.

I have used the following code:

#include "Arduino.h"
#include "ESP8266.h"
#include "SoftwareSerial.h"
#include "ArduinoJson.h"

#define ssid "mySSID"
#define pw "myPW"
#define IP "xxx.xxx.xxx.xxx"
#define URL "http://myurl.com/myaccesstoken"

int incomingByte;

void setup() {//I connect to wifi
  Serial.begin(115200);
  Serial.println("AT");
  delay(5000);
  analogReference(INTERNAL);
  if(Serial.find("OK")){
    Serial.println("AT+CWMODE=3");
    delay(1000);
    String WF=String("AT+CWJAP=\"")+ssid+"\",\""+pw+"\"";
    Serial.println(WF);
    delay(5000);}
}

void loop() {
  //JSON data creation
StaticJsonBuffer<200> jsonBuffer;
JsonObject& root = jsonBuffer.createObject();
root["flow"] = 2.54;
root["measured"] = "2017-08-14T06:16:03.418Z";
root.printTo(Serial);
delay(5000);
 // I start communication with server
 Serial.println(String("AT+CIPSTART=\"TCP\",\"") + IP + "\",80");
 delay(5000);
 Serial.println("AT+CPSTATUS");
 // I use HTTP protocol to POST the data
    Serial.println("AT+HTTPINIT");
    delay(2000);
    Serial.println("AT+HTTPPARA=\"CID\",\"1");
    delay(2000);
    Serial.println("AT+HTTPPARA=\"URL\",\"http://myurl.com/myaccesstoken\"");
    delay(2000);
    Serial.println(String("AT+HTTPPARA=\"CONTENT\",\"application/json"));
    delay(2000);
    Serial.println("AT+HTTPDATA=\" + 81 + \",1000"); //81 is the computed length of my JSON
    delay(2000);
    Serial.println("AT+HTTPACTION=1");
    delay(2000);
    Serial.println("AT+HTTPREAD");
    delay(2000);
    if(Serial.available() > 0)
        {
                // read the incoming byte:
                incomingByte = Serial.read();
                // say what you got:
                Serial.print("I received: ");
                Serial.println(incomingByte);
    }
    Serial.println();
    Serial.println("AT+HTTPTERM");

    delay(5000);
  }


texts:
I have a 16x2 LCD and I want to show a temperature: 23 ºC.

But the º symbol is not properly shown. It shows a strange character instead of the º symbol .


texts: ESP8266 Aes encryption using Arduino IDE

texts:
I'm trying to implement an AES encryption function on my ESP8266 controller, using Arduino ide and this aes library.
I finally made it work after many attempts but the output i get from the encryption function is only numerical and it doesn't correspond to other encryptions made by other softwares.

This is the code part relative to the AES encryption:

 #include <AES.h>

AES aes ;
byte *key = (unsigned char*)"0123456789010123";
unsigned long long int my_iv = 36753562;
 tempToken = RANDOM_REG32 % 10000;
    randomstr = String(tempToken);
    //answer = "{\"token\":\"" + randomstr + "\"}";
    byte plain[4];
    randomstr.getBytes(plain, 4);
    Serial.println(randomstr);
    Serial.println(plain[0]);
    Serial.println(plain[1]);
    Serial.println(plain[2]);
    Serial.println(plain[3]);
    byte cipher [48];
  //  aes.iv_inc();
    byte iv [N_BLOCK] ;
    aes.set_IV(my_iv);
    aes.do_aes_encrypt(plain, 48, cipher, key, 128, iv);
    String ciphertoken = "";
    for (int i = 0; i < 48; i++) {
      ciphertoken += cipher[i];
    }
    answer = "{\"token\":\"" + ciphertoken + "\"}";

It basically generates a random number between 0 - 9999, then converts it in a byte array (because aes function needs a byte array as input), then encrypt this byte array and prints the output, written in cipher byte array.

This is the output I get from it

6188
54
49
56
0
{"token":"521111513725521540120674957151112223103194250224197251261938514437131212302201813929189123134524113912554682501508415421130220"}

I can't understand if I did something wrong of if it is formatted in a strange way and if I can get the right encryption from it


texts:
Why would someone buy a 1sheeld?

Why not connect an Arduino to their smartphone using HC-06 bluetooth module and find an appropriate Android app, like for example RoboRemo. What is the advantage of using a 1sheeld?


texts:
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x30
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x0f
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x10
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x20
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x0f
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x10
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x30
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x0f
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x10
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x20


texts: Installing Arduino IDE in the new Ubuntu Disco Dingo

texts:
I tried installing the Arduino IDE in the newly released Ubuntu 19.04 Disco Dingo.
I downloaded the file from the official downloads page. I chmod +x ed the file and ran the install script. Then, it says:

Adding desktop shortcut, menu item and file associations for Arduino IDE...
rm: cannot remove '/usr/local/bin/arduino': No such file or directory
Removing symlink failed. Hope that's OK. If not then rerun as root with sudo.
touch: cannot touch '/root/.config/mimeapps.list': No such file or directory

/usr/bin/xdg-mime: 848: /usr/bin/xdg-mime: cannot create/root/.config/mimeapps.list.new:
Directory nonexistent`

Then, I again ran it as root user with su root but it still gave the same error...

Will this cause a problem..? I mean, I had prior issues related to uploading the sketch in earlier Linux IDE installations. Will this cause a problem...?
`


texts:
I have started programming Arduino in the last month. Now I'm working with a bluetooth module. But when I send some data from the Android device to the Arduino, it stays for a very short time and after that  immediately it becomes 0.

Why does it become 0? And how can I get rid of that problem?

Here is my code:

int x,y;

void setup()
{
  Serial.begin(9600);
}
void loop()
{
  if(Serial.available()>0)
  {
    x=Serial.parseInt();
    y=Serial.parseInt();
    Serial.print("x:");
    Serial.print(x);
    Serial.print("\n");
    Serial.print("y:");
    Serial.print(y);
    Serial.print("\n");
  }
  else
  {
    ;
  }
}

and here is the result:


texts: WS2812B strip stopped responding to control

texts:
I have a WS2812B LED strip (A clone of the Adafruit one I assume, it's from China via eBay) of 60 LEDs. When I got it, it was all fine - I could load the FastLED examples and they would work perfectly. I then tried to write something more custom, which didn't work for whatever reason. Upon re-loading the FastLED examples, I now get absolutely nothing from the strip.

It's being powered by an ATX computer power supply with ample amperage on 5V, and when I remove and then re-add the power connectors the strip does flash, indicating it's getting power and is capable of lighting up. It just feels like something I have done has caused it to enter a state where it won't respond to control.

I've also made sure my sketches are making it to the arduino by loading the inbuilt LED blink sketch, which works, then trying to switch back to a FastLED example which does nothing.

I'm kind of lost as to what could be wrong here.


texts: How to get the overall average of the data received

texts:
I have an arduino uno with two sensors. Voltage and current sensors. I need to get the average value of voltage and current each time the data is received. But i don't know how to add up the current and previous values and divide it to how many values that it has received.

Can someone help me, please? I need it for my project

This is the code i have made

void setup(){
Serial.begin(9600);
}
void loop(){
    int n=5;
    float sum=0;
    float ave=0;
    for(int x=0;x<n;x++){
        float volt=analogRead(A0);
        float voltage = map(volt,0,1023,0,2500);
        voltage/=100;
        Serial.print("Voltage: ");
        Serial.print(voltage,2);
       sum=sum+voltage;
       }
ave=sum/n;
Serial.print("Average: ");
Serial.print(average,2);
delay(3000);
}

But this only takes the average of 5 datas. I want to get the average of all data received.


texts: Arduino - Function -> return Cstr instead of string

texts:
I have following function for my Arduino:
String readLine() {
  String received = "";
  char ch;
  while (myFile.available()) {
    ch = myFile.read();
    if (ch == '\n' or ch == '\r') {
      if (ch == '\r')
      {
        //get rid of the \n
        myFile.read();
      }
      return String(received);
    } else {
      received += ch;
    }
  }
  myFile.close();
  hasFile = false;
  return received;
}

This function is used to return a line from a text file on a SD card. Since I do have to do quite some things on the returned string, I would like to have it as cstr instead of string to increase performance. But I am not able to convert this function to one that returns a Cstr. I tried this but it does not work:
char* readLine() {
  char* received = "";
  char ch;
  while (myFile.available()) {
    ch = myFile.read();
    if (ch == '\n' or ch == '\r') {
      if (ch == '\r')
      {
        //get rid of the \n
        myFile.read();
      }
      return received;
    } else {
      received += ch;
    }
  }
  return received;
}

Currently I am converting it after the function returns it, by using c_str(). It works, but I dont like it and would like to return a Cstr in the first place.
How can this be done?
Thank you!


texts: Can anyone send me a link tutorial about Arduino Object Oriented Programming? I want to learn Arduino, I am just a beginner.


texts: I²C between 2 Arduinos sends additional receive event

texts:
I hooked up two Arduino Nanos with I²C, using 3 wires between GND <-> GND, A4 <-> A4, A5 <-> A5Ω and 1kΩ pull-up resistors on A4 & A5.

When I use the following code to communicate between them I get a weird empty receive event.

master.cpp

#include <Arduino.h>
#include <Wire.h>

#define SERIAL_BAUD 9600

#define I2C_SLAVE_ADDRESS 8

void setup () {
    Wire.begin();
    Serial.begin(SERIAL_BAUD);
}

void getFromState (unsigned char state) {
    Wire.beginTransmission(I2C_SLAVE_ADDRESS);
    Serial.print("s");
    Serial.print(Wire.write(state));
    Serial.print("e");
    Serial.print(Wire.endTransmission());
    delay(5000);
    Wire.requestFrom(I2C_SLAVE_ADDRESS, 2);
    int c = (unsigned char) Wire.read();
    Wire.flush();
    Serial.print("r");
    Serial.println(c);
    Wire.endTransmission();
}

void loop () {
    Serial.println("loop");
    getFromState(0);
    delay(10000);
    getFromState(1);
    delay(10000);
}

slave.cpp

#include <Arduino.h>
#include <Wire.h>

#define SERIAL_BAUD 9600

#define I2C_ADDRESS 8

unsigned char state = 0;

void requestEvent () {
    Serial.print("Request ");
    Serial.println(state);
    Wire.write(state);
}

void receiveEvent (int amount) {
    Serial.print("a");
    Serial.print(amount);
    Serial.print("r");
    state = (unsigned char) Wire.read();
    Serial.println(state);
}

void setup() {
    Serial.begin(SERIAL_BAUD);
    Wire.begin(I2C_ADDRESS);
    Wire.onRequest(requestEvent);
    Wire.onReceive(receiveEvent);
}

void loop() {
    delay(10);
}

Serial Output Master After 1.5 Loops

loop
s1e0r0
s1e0r1
loop
s1e0r0
s1e0

Serial Output Slave After 1.5 Loops

a1r0
Request 0
a0r255
a1r1
Request 0
a0r255
a1r0
Request 0
a0r255
a1r1

Question

Why is there an empty receive event a0r255 after every request? Is that normal? Am I doing something wrong? Is this some sort of hardware issue?

EDIT: I opensourced this project here, take a look if you want to!


texts: Using a L2938D Motor Driver Module. (Not IC, Module)

texts:
I have been trying to use my newly bought L293d Motor Driver Module to run motors(a single motor in this test case, simple 5V toy motor) from my Arduino UNO. Thing is, this is an entire module, not just the IC (in which case there are many tutorials available). So I was following this tutorial to try and get my motor running.

Here is the tutorial - http://www.instructables.com/id/Arduino-and-L293D-Robot-Part-1-/?ALLSTEPS
Here's what the module looks like -

There are 6 Pins on the module, which bring out the 6 inputs, EN1, EN2, IN1, IN2, IN3, IN4. Now since I am using only one motor, I connected my motor to the OUTPUT 1 & 2 header given on the module. I then take the 5V and GND from Arduino and connect them to my Module's 5V and GND header, (leaving the 12V one empty), I thought that this would be enough as my motor is also of 5V.
I then connected the IN1 and IN2 to the pins 7 & 8 on my Arduino and used the following code-

// Simple code to make the motor turn
int RightMotorForward = 7;
int RightMotorReverse = 8;

void setup()
{
  pinMode(RightMotorForward, OUTPUT);
  pinMode(RightMotorReverse, OUTPUT);
}

void loop()

{
   digitalWrite(RightMotorForward, HIGH);
   delay(10000);

   digitalWrite(RightMotorForward,LOW);
   delay(1000);
}

Nothing happened. The motor didn't work and I have no idea why. I've gone through the entire datasheet for L293D but I found nothing that could help me. I suspect that it has something to do with the EN1 pin, but I don't really know how to use it, the tutorial said to connect it to 5V, which I tried but no results. So where am I making the mistake? How do I get this to work?


texts:
I am using this code and I can not save the output of the hash function to an array of char. Can you help me how to do that?

#include "sha256.h"
#include <Arduino.h>
#include "./printf.h"

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()
{ String FinalStr="1234567890";
Sha256.init();
  Sha256.print(FinalStr);
  printHash(Sha256.result());
}
void loop()
{

}


texts: I'm trying to upload a sketch to my arduino uno, but I get the Error-Message "avrdude: stk500_recv(): programmer is not responding"

texts:
Arduino: 1.8.13 (Linux), Board: "Arduino Uno"

Sketch uses 444 bytes (1%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

I selected the right board (Arduino Uno)
I selected the right port
I selected "USBasp" as programmer
I reset the board multiple times
I have uploaded to the same port multiple times before without getting an Error
I disconnected the USB-cable multiple times and used a different one
I don't get the Error Message on a different board (also Arduino Uno)
When I'm trying to upload with the serial Monitor open i see an orange lamp (RX lamp) blinking in the same speed the Errors are given
When I'm trying to "Burn Bootloader" I get following Error:

Arduino: 1.8.13 (Linux), Board: "Arduino Uno"

avrdude: error: could not find USB device with vid=0x16c0 pid=0x5dc vendor='www.fischl.de' product='USBasp'
Error while burning bootloader.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.


texts: ESP32 HCI command for setting BLE TX Power

texts:
Does anyone know if there's an HCI command for setting the TX and the advertising power for BLE on an ESP32?

I have a Nano 33 IoT and a MKR 1010, and it has its power set annoyingly low for advertising and transmission.  The library that I'm using is ArduinoBLE, which uses HCI to communicate with the ESP32.

I believe that espressiv allows the power level to be set using their dev kit, and I know that other vendors (e.g., TexasInstruments) provide extensions to HCI for setting power levels, but I haven't been able to find an HCI command for ESP32 anywhere.

Any ideas on other ways that I could do this other than HCI would be welcome too (e.g., other libraries for BLE that would work with the MKR and Nano series of boards, but would allow setting the power level for advertising and transmission.


texts:
I am trying to use D0/D1 as normal IO pins but DigitalWrite does not work as on an Arduino UNO.

I know the SAMD21G has SERCOM but I can't seem to find an example of not using D0/D1 as an UART port.

EDIT ** Code I have tried:

#define MYMASK 0x00000C00
void setup() {
  REG_PORT_DIRSET0 = MYMASK; // Direction set to OUTPUT
  REG_PORT_OUTSET0 = MYMASK; // set state of pin(s) to TRUE (HIGH)
  delay(1000);
  REG_PORT_OUTCLR0 = MYMASK; // set state of pin(s) to FALSE (LOW)
}

void loop() {
}


texts: Custom bootloader for battery level indicator

texts:
For a project I need to be able to read the battery level of the device regardless of the sketch currently running.
For this I plan on adding a custom routine in the Arduino bootloader that reads the battery level and shows it can be accessed even when the current sketch is overwritten with another sketch.

Is creating a custom bootloader a good solution for this? If so how should I go about create that bootloader?

Edit:
The battery level will be shown using 3 leds indicator every time a specific button is pressed; I don't want to store the battery level. I need this to happen in every sketch, that's why I think I should do this on the bootloader, having that code on the sketch isn't an option. This is needed because I am developing a custom board and this function will be default on each board.


texts: Atmega328 and 4Digit 7 Segment ghost blinking!

texts:
I hooked up 4 7Seg leds (CC) with NPN transistors on the cathode of each digit. I am using 74HC595 shift register connected in the circuit in a pretty common fashion. The code I am running is the basic scanning code for the 7seg. The problem is that I see the scanned numbers on other LED digits too. Attached is the image. I call them "ghosts". The circuit I am using has an Atmega328 with an internal 8MHz Osc. The resistors on the segments are 220Ohm and 4 BC547's on the cathodes of the digits with 1kOhm resistors on their base.

below is the code:
void loop() {

      cathode_high(); // blank the screen

      break_number(number);

      display_number();
     delay(1);

}

void break_number(int num) { // seperate the input number into 4 single digits

  first_digit = num / 1000;
  digits[0] = first_digit;

  int first_left = num - (first_digit * 1000);
  second_digit = first_left / 100;
  digits[1] = second_digit;
  int second_left = first_left - (second_digit * 100);
  third_digit = second_left / 10;
  digits[2] = third_digit;
  fourth_digit = second_left - (third_digit * 10);
  digits[3] = fourth_digit;

}

void display_number() { //scanning

  cathode_high();
  digitalWrite(latch, LOW);
  shiftOut(data, clk, LSBFIRST, numbers[digits[count]]);
  digitalWrite(CAS[count], HIGH);
  digitalWrite(latch, HIGH);
  count++;
  if (count == 4) {
    count = 0;
  }
}

void cathode_high() { //turn off all 4 digit
  digitalWrite(CA_1, LOW);
  digitalWrite(CA_2, LOW);
  digitalWrite(CA_3, LOW);
  digitalWrite(CA_4, LOW);
}
Any help would be highly appreciated. Thanx in advance!


texts:
I want to gain from recent advice from this forum by re-doing my project using 'state machine' logic if possible, in an effort to reduce wasted processor time and variables usage.

I'm starting from Nick Gammons 'state machine to process input from the serial port' example http://www.gammon.com.au/statemachine, which shows all the different possible combinations for all the special control character 'events' against all the possible machine states - essentially a 2-dimensional grid.

I've refined my goal to the processing of serial input in a format of "command  [parameters]  [options]", similar to a DOS command-line format, eg:  DIR  "c:\program files"  /w /s. This would free me from needing large Buffer[] and Header[] string, and avoides any parsing,

Therefore my event control characters are space, comma, single-quote, double-quote, forward-slash, Carraige Return, and my 'states' are NULL, COMMAND, PARAMETER, OPTIONS

The OPTIONS state adds characters to a temporary option[] string until a comma or space delimiter or Carraige Return causes that option to be processed as appropriate, perhaps saving its value to a recognised variable.

The COMMAND and PARAMETER 'states' add characters to their corresponding command[] and parameters[] strings, including the special control characters if they are contained within either single or double quotes (thereby allowing quotes as part of a string if used within a pair of the other type).

So there appears to be a second state machine needed for NoQuotes, SingleQuotes and DoubleQuotes to modify the operation of the COMMAND, PARAMETER and OPTIONS states.

This is where I run out of neurons, because all I see is an impossibly complex 2-machine-state 3-dimensional grid with too many possible permutations.

But I suspect there must be a very practical way to implement this, because it lies at the heart of almost all command-line utilities dating back to a time when processor power and memory availability were scarcer than hens teeth, and those old DOS command-line utilities needed to be as mimimal as was possible, including their command-line parsing.

So can anybody suggest a feasible model (machine-state or otherwise) for getting command-line type format from input?

UPDATE

Oh dear... I've just seen another complication I hadn't spotted before, which is that '/' options are not necessarily always at the end, which means that except if the options state changes by carraige-return, options state change by delimiter have to return to the state prior to the options state change (phew, I hope that makes some sense).  Anyway, I think it's back to drawing board because this approach seems likely to be too complicated, as the 2 answers already suggest.


texts: Bluetooth transfer problem with big files

texts:
I want to send some data from an Arduino Mega to an android device via bluetooth (HC-06). I have installed some sensors whose values are frequently written in an SD card. Every time a new string line is added in a text file of the SD card. This is the format of the line

27/5/2015,11:55:00,34.00,27.00,42.50,26.80,47.80,26.00,24.62,24.12,26,0,0,708,1023,1023,1023,1023,10.5,10.5,10.5,10.5

and this is part of the code. I send from a bluetooth terminal the string "download" and after that the text file is opened and every line is readed and sent to the android device via bluetooth.

void loop(void){
    while(Serial1.available()) {
       character = Serial1.read();
       content.concat(character);
     }

if (content == "download") {
    Serial.println(content);
    content = "";
    read_from_SD_Card();
    }
    ........................
    ........................
    ........................
}

void read_from_SD_Card(){
    myFile = SD.open("test.txt");
    if (myFile) {
        Serial1.println("test.txt:");

        while (myFile.available()) {
            Serial1.write(myFile.read());
      }
      myFile.close();
    }
else {
  Serial1.println("error opening test.txt");
  }
}

The problems are:

the data are downloaded only after an upload of the sketch has been done. (I can't upload the sketch once and download the data from time to time)
No more than 10-20 lines can be downloaded. With bigger files the downloading seems to slow down and finally stops after a few lines.

Any thoughts would be appreciated.


texts:
I read in this atmega328p datasheet the following on page 308:
From sect. 28.4:

By default, the successive approximation circuitry requires an input
clock frequency between 50kHz and 200kHz to get maximum resolution. If
a lower resolution than 10 bits is needed, the input clock frequency
to the ADC can be higher than 200kHz to get a higher sample rate.
The
ADC module contains a prescaler, which generates an acceptable ADC
clock frequency from any CPU frequency above 100kHz. The prescaling is
selected by the ADC Prescaler Select bits in the ADC Control and
Status Register A (ADCSRA.ADPS). The prescaler starts counting from
the moment the ADC is switched on by writing the ADC Enable bit
ADCSRA.ADEN to '1'. The prescaler keeps running for as long as ADEN=1,
and is continuously reset when ADEN=0.
When initiating a single ended
conversion by writing a '1' to the ADC Start Conversion bit
(ADCSRA.ADSC), the conversion starts at the following rising edge of
the ADC clock cycle.
A normal conversion takes 13 ADC clock cycles.
The first conversion after the ADC is switched on (i.e., ADCSRA.ADEN
is written to '1') takes 25 ADC clock cycles in order to initialize
the analog circuitry.

By required bandwidth is 120 kHz, and 5 bit accuracy will suffice for my purpose. So, I understand that I can achieve this by changing the prescaler to a lower division number, thus increasing the clock frequency fed into the ADC (as per the diagram in the aforementioned document).
However, the document only specifies the min and max times required for ADC conversion for 50 kHz (12 to 280 microseconds at 50kHz bandwidth).
My question: Given my requirement of 120kHz bandwidth, what is the lowest prescaler division value I should use to guarantee ADC completion time to within 1/120kHz seconds (8.3us)?
EDIT: This is another question I have: Why does the accuracy change when using a lower divider value? Surely we are simply changing the clock frequency fed into the ADC converter, not the ADC algorithm itself; so why should the bit accuracy change?


texts: Why am I receiving random input values in my Arduino?

texts:
I want to use a switch for my Arduino using digitalRead(), but I keep receiving random inputs. Whenever I connect energy to that pin, it always returns HIGH, but otherwise it goes completely random.
I have tried using a resistor for the input pin, but that didn't seem to help. I am using an Elegoo UNO, and the input pin I am using is pin 2. Here's my code in case you need it:
const int switchPin = 3;

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

void loop() {
  // put your main code here, to run repeatedly:
  if (digitalRead(switchPin) == HIGH){
    Serial.println("on");
  }

  else{
    Serial.println("off");
  }
}


texts: Cast from uint8_t* to char - loses precision

texts:
I am trying to decode a received (via websocket) message (JSON) on my ESP8266.

The websocket library provides the data as uint8_t. The JSON library only understands char arrays. As far as I know uint8_t is basically char.

I am getting this error:
cast from 'uint8_t* {aka unsigned char*}' to 'char' loses precision [-fpermissive]

The websocket-function provides the payload as uint8_t:

void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length)

The JSON Decoder wants a char arr, as provides in the sample:

char json[] =
"{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}";

How to "convert" the uint8_t to char[]?

Here is my full code:

#include <ArduinoJson.h>
#include <ESP8266WiFi.h>
#include <WebSocketsServer.h>

WebSocketsServer webSocket = WebSocketsServer(81);
StaticJsonBuffer<200> jsonBuffer;

void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length) {

    switch(type) {
        case WStype_DISCONNECTED:
            Serial.printf("[%u] Disconnected!\n", num);
            break;
        case WStype_CONNECTED:
            {
                IPAddress ip = webSocket.remoteIP(num);
                Serial.printf("[%u] Connected from %d.%d.%d.%d url: %s\n", num, ip[0], ip[1], ip[2], ip[3], payload);

        // send message to client
        webSocket.sendTXT(num, "Connected");
            }
            break;
        case WStype_TEXT:
        {
            Serial.printf("[%u] get Text: %s\n", num, payload);
            JsonObject& root = jsonBuffer.parseObject((char)payload);
            // send message to client
            // webSocket.sendTXT(num, "message here");

            // send data to all connected clients
            // webSocket.broadcastTXT("message here");
        }
            break;
        case WStype_BIN:
            Serial.printf("[%u] get binary length: %u\n", num, length);
            hexdump(payload, length);

            // send message to client
            // webSocket.sendBIN(num, payload, length);
            break;
    }

}

void setup()
{
  Serial.begin(115200);
  Serial.println();
  IPAddress ip(192, 168, 178, 51);
  IPAddress gateway(192, 168, 178, 1);
  IPAddress subnet(255, 255, 255, 0);
  WiFi.config(ip, gateway, subnet);
  WiFi.begin("MyWifi!", "passpasspass");

  Serial.print("Connecting");
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println();

  Serial.print("Connected, IP address: ");
  Serial.println(WiFi.localIP());
  webSocket.begin();
  webSocket.onEvent(webSocketEvent);
}

void loop() {
   webSocket.loop();
  }


texts: How to send float numbers from python3 with struct to arduino

texts:
I have searched several questions and through google but could not find a solution. I am simply trying to send a float number from python3 with struct to arduino or if there is any other ways other than processing a char array at the arduino side because it is very slow in my opinion..

My arduino code:

void setup() {
  // initialize the serial communication:
  Serial.begin(9600);
}

void loop() {

  unsigned long t = millis();
  float x = analogRead(A3);
  float y = analogRead(A2);
  float c = Serial.read();
  Serial.println(c);
  //Serial.print(t/1000.0);
  //Serial.print(" , ");
  //Serial.print(x);
  //Serial.print(" , ");
  //Serial.println(y);

  // wait a bit for the analog-to-digital converter to stabilize after the last
  // reading:
  //delayMicroseconds(200);
  //delay(2);
  delay(250);
}

My python3 code :

import serial

import struct

arduino = serial.Serial('/dev/ttyACM0', 9600)
data = arduino.write(struct.pack('f', 111.32))
while True:
#    arduino.write(b"123")
    data = arduino.write(struct.pack('f', 111.32))

Getting the serial output as :

163.00
222.00
66.00
215.00
163.00
222.00
66.00
215.00
163.00
222.00
66.00
215.00
163.00

How can i solve my problem ?

EDIT : I changed the arduino code according to the answer the new arduino code is

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

void loop(){
  while(Serial.available() >= 3){

    f = Serial.read() << 24;
    f = ((unsigned long) f) | (Serial.read() << 16);
    f = ((unsigned long) f) | (Serial.read() << 8);
    f = ((unsigned long) f) | Serial.read();
    Serial.println(f);
  }
  Serial.println(f);
}

However, the output is now as such:

ovf
ovf
ovf
ovf
ovf
ovf
ovf
4294941184.00
4294941184.00
4294941184.00
4294941184.00
4294941184.00
4294941184.00
4294941184.00


texts: Editing a particular position in a file stored in SD card

texts:
I am trying to store some variables in a text file which is saved in a SD card, using the SD library. Every time my program runs, it load the values of those variables from the file. After a few minutes, my program will attempt to change the value of some variables (not all).

This is what I would in a C program. I would locate the position (using position()) where the values to be edited is present, and then using the seek() function I would write at the given position thus overwriting the file.

Each variable is stored in a separate row. But for some reason the program only writes at the end of the file, even if I have moved the file pointer elsewhere. How can I do the above task?

A simple example of the code is as follows:

#include <SD.h> //Load SD library

int chipSelect = 53;
File file;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(chipSelect, OUTPUT); // chip select pin must be set to OUTPUT mode

  Serial.print("Welcome!");
  Serial.println();

  bool initialization_state = SD.begin(chipSelect);
  delay(400); // SD card needs sometime to intialize

  if (!initialization_state) { // Initialize SD card
    Serial.println("Could not initialize SD card."); // if return value is false, something went wrong
  } else {  // if return value is true
    Serial.println("SD card initialized");
  }

  SD.remove("misc.txt");
  file = SD.open("misc.txt",FILE_WRITE);
  file.print("Once you know the central idea and a rough plan for your paragraphs, you need to arrange them in a certain manner to get your story across.");
  file.println();
  file.print("Following are some possible ways of organizing your paragraphs.");
  file.println();
  file.print("Narration: Tell a story. Go chronologically, from start to finish. Description: Provide specific details about what something looks, smells, tastes, sounds, or feels like.");
  file.println();
  file.print("Organize spatially, in order of appearance, or by topic. Process: Explain how something works, step by step. Perhaps follow a sequence—first, second, third.");
  file.close();
  read_file();
  Serial.print("Read?");
  Serial.println();

  update_file();
  read_file();
}

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

void read_file() {
  Serial.println("--- Reading file ---");
  file = SD.open("misc.txt", FILE_READ);

  char character;
  while( (character = file.read()) != -1) {
    Serial.print(character);
  }
  Serial.println();
  file.close();
}

void update_file() {
  file = SD.open("misc.txt", FILE_READ);
  char character;
  while( (character = file.read()) != '\n') {}
  byte pos = file.position();
  file.close();

  file = SD.open("misc.txt", FILE_WRITE);
  file.seek(pos);
  file.print(" Love, love, love.");
  file.close();
}

In this program I am attempting to overwrite the second line. The while loop breaks at the first newline character. I store the location of the first character in the second line in a variable pos. Then I open the file object for writing, I seek the position where I want to write (using file.seek(pos) ) and then I print into the file. But when I read the file, the text "Love, love, love." is written at the end.

I am using the linux Arduino IDE 1.8.9.


texts: Having trouble with motor shield running off external power source

texts:
I apologize if I don't immediately give important info, I'm very new to arduino's/circuity of any kind.  I'll try to include as much info as possible.

Some preface:
I'm currently working on a project that generates electricity using TEG's (Thermoelectric generator). The setup I currently have is able to output upwards of 9V. The motor I'm using is able to run when directly connected to the TEG wires, sp they produce enough electricity to work. Due to the nature of the project, a stopping mechanism is being used via a photoresistor and an LED. Essentially when the light signal picked up by the photoresistor is low  enough,  power is cut to the motor.

So up until recently, the motor and the Arduino board/motor shield (Arduino UNO, Arduino Motor Shield Rev3) were being run using a 9V battery. Everything worked correctly, the motor would start when needed and stop when needed. Once I switched to the TEG's the set up stopped working (motor stopped running). What is weird is that if I connect a voltmeter to channel 1 of the motor shield, I read 6V-7V (some voltage drop but not drastic) when the LED was on and 0 when the led was off. So everything seemed to still be working, but the motor itself just won't actually run. In fact, when the LED is on, it makes a very faint noise for a second but doesn't run.

The only thing I can think of is that the current being produced by the TEG's is only enough to power the motor when directly connected, but when wired indirectly through the board thus powering the board, it no longer has enough amperage.

I included the code I wrote for it, which worked fine with a 9V battery powering the motor/board.

const int sensorPin = A5;
const int ledPin = 5;
int lightLevel;

void setup(){
  Serial.begin(9600);
  pinMode(12,OUTPUT);
  pinMode(9,OUTPUT);
  pinMode(ledPin, OUTPUT);
}

void loop(){
  lightLevel = analogRead(sensorPin);
  lightLevel = constrain(lightLevel, 0, 800);
  Serial.println(lightLevel);

  if(lightLevel < 200){
    digitalWrite(9,LOW);
    digitalWrite(12,HIGH);
    analogWrite(3,255);
  }
  if(lightLevel > 200){
    digitalWrite(9,HIGH);
    analogWrite(3,0);}
}


texts:
(This might be more of a common C question)

I want to test several conditions in an IF-sentence

if(variable) {            // fastest check
  if(register) {          // a bit slower
    if(read_peripheral) { // very slow check
      // [do something]
    }
  }
}

It seems obvious that I want to start with the fastest check, and move on to the slower ones afterwards, potentially avoiding to check them if the above was false.

Now since I need to check quite a few conditions, I'd like to know if the following is the same, or if all conditions will be evaluated prior to making a decision?

if(variable && register && read_peripheral) {
  // [do something]
}


texts: How to properly link an Arduino and its sensors

texts:
To finalize a prototype, I would like to have a proper structure containing the arduino (uno here), its shields and its sensors. I would like the sensors to be soldered to the arduino+shields block, but the sensors were sold on a small separate PCB (example).

What is the recommended method to have a strong, clean link between the two ?


texts: Unpredictable behavior on parsing key-value delimited input from serial

texts:
I am having trouble with a "simple" command parser; I'm guessing I'm doing something wrong with memory allocation - appreciate any pointers :)

For context: I'm running on an Arduino Uno (if it matters). The commands I expect are of the form <key1=value1;key2=value2;key3=value3>. For simplicity here (as well as for my own failed attempts at debugging), I've removed everything extraneous, so that this code just prints back to the serial monitor whatever the current value associated with the key "text" is every time a command enclosed in < > is encountered.

This seems to work correctly until after the first time the key is found; then it behaves somewhat unpredictably - haven't yet been able to discern the pattern.  But, for instance, if I send:

<a=5>
-> EMPTY
<b=7;text=here;d=9>
-> here
<d=abc>
-> here
<d=ghi;e=afds>
-> afds

That last displayed value is wrong, since no new key of text was sent over serial. The complete code is here:

// command indicators
char START_MARKER = '<';
char END_MARKER = '>';

const int MAX_KEY_VALUE_PAIRS = 3;  // maximum number of key-value pairs in message
const int MAX_ELEMENT_CHARS = 25;  // the maximum number of characters (+1 for terminator) in a key or a value

// message format: <key1=value1;key2=value2;key3=value3>
const int MAX_MESSAGE_CHARS = (MAX_KEY_VALUE_PAIRS * (MAX_ELEMENT_CHARS + 1)) * 2 + (MAX_KEY_VALUE_PAIRS - 1) + 2;  // maximum message size

char received_chars[MAX_MESSAGE_CHARS];  // <- EDIT#1
char received_chars[30] ={'\0'};
bool new_data = false;

char *text;  // the value identified by the "text" keyword, i.e.: in <text=abc;time=814a>, text would be abc.

void ParseData(char *str) {
  // This picks off the ;-delimited key-value pairs and assigns them to a multi-dim array
  char * pch;
  int pairs_count = 0;
  char config[MAX_KEY_VALUE_PAIRS][2][MAX_ELEMENT_CHARS];

  pch = strtok(str, "=");

  while (pch != NULL)
  {
    strcpy(config[pairs_count][0], pch);
    pch = strtok(NULL, ";");
    if (pch == NULL) break;

    strcpy(config[pairs_count][1], pch);
    pairs_count++;
    pch = strtok(NULL, "=");
    if (pch == NULL) break;
  }

  for(int i=0;i<pairs_count;i++) {
    if (strcmp(config[i][0], "text")==0) text = config[i][1];
  }
  Serial.println(text);
}

void ReadSerial(){
  // After calling ReceiveText to empty the buffer, if a complete command has been found,
  // parse that command.
  new_data = ReceiveText();
  if (new_data == true) {
    char temp_chars[MAX_MESSAGE_CHARS];  // temporary array for use when parsing
    strcpy(temp_chars, received_chars);
    received_chars[0] = '\0';  // <- EDIT#2
    ParseData(temp_chars);
  }
}

boolean ReceiveText() {
  // This dumps the characters on the buffer so far received_chars, searching for an END_MARKER
  // along the way; if it finds one, it goes back to find a START_MARKER; if that is also found,
  // the string within is the ;-delimited set of key value pairs
  static boolean recv_in_progress = false;
  static byte ndx = 0;
  char rc;

  boolean new_data = false;
  while (Serial.available() > 0 && new_data == false) {
    rc = Serial.read();

    if (recv_in_progress == true) {
      if (rc != END_MARKER) {
        received_chars[ndx] = rc;
        ndx++;
        if (ndx >= MAX_MESSAGE_CHARS) {
          ndx = MAX_MESSAGE_CHARS - 1;
        }
      } else {
        received_chars[ndx] = '\0'; // terminate the string
        recv_in_progress = false;
        ndx = 0;
        new_data = true;
      }
    } else if (rc == START_MARKER) {
        recv_in_progress = true;
    }
  }
  return new_data;
}

void setup() {
  Serial.begin(9600);
  text = (char*)malloc(25);
  strcpy(text, "EMPTY");
  received_chars[0] = '\0';
}

void loop() {
  ReadSerial();
}

Thanks!


texts: What's the function of this transistor on Arduino Mega?

texts:
I am trying to get information about the transistor on the Arduino Mega board below:

It says "340P" on the transistor. I want be able to know which model transition is this so that I can check its documentation. It also want to know what it is driving or its function on the Arduino board.


texts: How to find integer inside a file with STRNCMP

texts:
I'm trying to compare the int number 18 with strcmp but give to me wrong result, the program looking for char 18 and not for integer 18, how i can look for an integer with strcmp?

/*
 SD card read/write

This example shows how to read and write data to and from an SD card file
The circuit:
* SD card attached to SPI bus as follows:
** MOSI - pin 11
** MISO - pin 12
** CLK - pin 13
** CS - pin 4

created   Nov 2010
by David A. Mellis
modified 9 Apr 2012
by Tom Igoe

This example code is in the public domain.

*/

#include <SD.h>

File myFile;
char buf[10];

char bufStringa[24];

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

 Serial.print("Initializing SD card...");
 // On the Ethernet Shield, CS is pin 4. It's set as an output by default.
 // Note that even if it's not used as the CS pin, the hardware SS pin
 // (10 on most Arduino boards, 53 on the Mega) must be left as an output
 // or the SD library functions will not work.
  pinMode(10, OUTPUT);

 if (!SD.begin(53)) {
   Serial.println("initialization failed!");
   return;
 }
 Serial.println("initialization done.");

 // re-open the file for reading:
 myFile = SD.open("test.txt");
 if (myFile) {
   Serial.println("test.txt:");

   // read from the file until there's nothing else in it:
   int id=18;
   while (myFile.available()) {
      myFile.read(buf,2);
       if(strncmp(buf, id, 2) == 0) // i think the system give to me te char 18 and not the number 18 how to do this?
       {
           Serial.println("Match!");
           for(int i=0;i<10;i++)
           {
            Serial.print(buf[i]);

           }
            myFile.read(bufStringa, 24);
            for(int i=0;i<24;i++)
           {
            Serial.print(bufStringa[i]);

           }
          break;
       }
   }
   // close the file:
   myFile.close();
 } else {
  // if the file didn't open, print an error:
   Serial.println("error opening test.txt");
 }
}

void loop()
{
  // nothing happens after setup
}


texts: motor affecting time calculation between hardware interrupts

texts:
My robot uses an Arduino Mega 2560. It has 6 IR receiver modules connected to its 6 external pins namely 2, 3, 18, 19, 20, and 21.I have connected the Pololu MC33926 dual motor driver arduino shield to my arduino(here is the connections diagram : https://www.pololu.com/docs/0J55/3.c ). I generate a 56KHz IR signal with an LED from another Arduino. The IR receiver modules convert the 56KHz signal into a active low digital signal. My signal consists of a signature bit followed by 32 bits of data. a binary 1 is represented by a signal of length 1200 uS and a binary 0 is represented by a 600uS signal with intervals of 600uS. I employed a state machine in my code which checks the duration of time between falling edge and rising edge. and vice versa and compares it to the duration expected. If anything is not expected it discards as noise and goes back to the idle state. If the duration is as expected it goes to the next state and then takes in the entire 32 bits and converts this binary format into a decimal value. I print this value on a 7 segment display on my robot. It works perfectly when the motor's are not running.
      Now this is the case when the motors are running. It does not receive the signal. I have tested every component individually and these are the results:

The receivers still receive the signal perfectly, and their output to the Arduino is also as expected. No problem there.
Earlier the Arduino was being powered through the Motor driver. Just to make sure that was not the problem I separated the Arduino's power supply from that of the motor driver. Still the same issue, i.e. the robot does not receive a valid signal(at this point i realized the arduino receives a valid signal but isnt able to decode it accurately).
We then printed out the values of time differences between each rising and falling edge on the interrupt pins. These values seem correct and within the tolerance range when the motors are switched off. But when the motors are switched on these values are not right. Of the 32 duration's measured, atleast two are not right(for eg. instead of 300 uS it calculated 88uS) due to which the signal is being discarded as invalid.
I thought that the PWM being generated to control the speed of the motors on digital pin 9 and digital pin 10(OC2B AND OC2A). Even though the PWM signals were being generated(without the motors connected) the signal was still being read as valid and the robot was receiving the signal. So its not that either.

The only anomaly I have found are the readings of the durations of the interrupt intervals. Can somebody please tell me what connection I have done wrong. Its mostly not with the program since it works otherwise. Something with the motor is making the Arduino act weirdly. Any help will be greatly appreciated. I have to scale up these robots to build a swarm and I am still stuck in the first step.

Thanks a lot.


texts: How fast should I be able to write to AT45DB321D flash memory?

texts:
I checked the AT45DB321D datasheet and it says it operates at either 66 MHz oder 33 MHz. Both of these speeds are higher than what an Arduino Nano supports (my google fu fails me here, but according to the Arduino SPI doc it's probably on the order of 4 MHz).

According to the datasheet

  Data can be clocked in from the input pin (SI) into either buffer 1 or buffer 2. To load data into the standard DataFlash buffer (528 bytes), a 1-byte opcode, 84H for buffer 1 or 87H for buffer 2, must be clocked into the device, followed by three address bytes comprised of 14 don’t care bits and 10 buffer address bits (BFA9-BFA0). The 10 buffer address bits specify the first byte in the buffer to be written. [...] Data will continue to be loaded into the buffer until a low-to-high transition is detected on the CS pin.

Which means to write a single byte I would need

1 opcode byte
3 address bytes
1 data byte

totaling 5 bytes or 40 bits which at 4 MHz yields 10 µs.

My code, as below, yields roughly 48 µs per byte (outputs a duration of ~12380 µs for transfering 256 bytes). I'm using the DataFlash library.

#include <SPI.h>
#include "DataFlash.h"

static const int csPin    = 10;
static const int resetPin = 8;
static const int wpPin    = 7;

DataFlash dataflash;

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

  SPI.begin();

  dataflash.setup(csPin, resetPin, wpPin);
  dataflash.begin();

  long start = micros();
  dataflash.bufferWrite(0, 0);
  for(int i = 0; i <= 255; i++) {
    SPI.transfer(i);
  }
  long afterBuffer = micros();

  Serial.print("Writing 256 values to buffer: ");
  Serial.println(afterBuffer - start);
}

void loop()
{
  // nothing
}

It's very likely I'm missing something, but especially if I want to transfer larger chunks of data at once I'd like to speed up that process a bit. Creating a 256 byte buffer and writing it all at once

// outside time measurement
uint8_t buffer256[256];
for(int i = 0; i <= 255; i++) {
  buffer256[i] = i;
}
// inside time measurement
SPI.transfer(buffer256, 256);

takes roughly the same time.

tl;dr: Is everything working correctly/what am I doing wrong? How can I speed up writing to a flash chip using an Arduino Nano?


texts: How do I attach 4 input pots to arduino?

texts: I am making an arduino game and the requirement is that my arduino reads 4 analog values from the pots. I dont know whether I should use an external battery supply or the 5V from the duino' itself. I dont want my ICs to get fried or nothing happening at all.


texts: Problems with green TWI (I2C) port on Arduino Braccio Shield

texts:
Summary: The green TWI/I2C port on my Braccio shield I2C port hasn't worked for me so far. Looking for advice or information please.
Detail:
I'm using the Arduino (Tinkerkit) Braccio robot arm for self education. It comes with a Uno based Braccio Shield. Tinkerkit no longer seems to be in business and documentation is a bit scarce. The shield uses KF2510 style connectors for servos (orange), inputs (white), serial (yellow) and importantly for my question a TWI/I2C port (green).

The green four pin TWI/I2C connector provides GND, +5V, SDA (A4), SCL (A5). However the SDA and SCL connections are reported to not be direct, but that "a very tiny chip (located next to the I4 connector) buffers between the green connector and the Arduino pins SDA and SCL" . A photo of the chip described is below.

Contrary to the reports of a "buffer" studying the schematic shows a level shifter PCA9306TI and two sets of 10K pullup resistors (R7,R8 and R11,R12) on the bus on both sides of the chip. VREF2 on the outboard side of the chip has a R9 220K resistor to +5V.

The other side of my I2C connection was an Arduino Pro-mini 5V. I was never able to get it working using the green port described, but it works fine directly hooked into SCL and SDA bypassing the level shifter.
My questions (sorry for the long lead up) are:

Has the green TWI port been level shifted to expect ~3V? (Only really came to this conclusion writing this all up clearly).
If I want to change the green TWI port to 5V I2C can I replace R9 220K with a zero ohm jumper?
The 10K pullups (R7,R8 and R11,R12) seem larger than anticipated (I had anticipated about 4.7K for 5v or about 2.4 for 3V)? Can they be removed and left open if I have a single set of pullups elsewhere on the bus? Or better suggestions?

Thanks!
Update 2021/01/30
Well my I2C debugging skills are improving researching this! As a test bed I set up a clean working I2C bus with two MCU's running the Arduino Example Master/Writer Slave/Receiver sketches by Nicholas Zambetti. I tested the I2C signal on the oscilloscope to make sure it was clean. All good. To that test bed I connected the Braccio shield (5V, GND, SCL, SDA). Connecting the Braccio shield changes the I2C signal in interesting ways, with partial strength (runt) pulses, and round shoulder slow rises. Connecting via the green TWI port seems to accentuate the runt pulse aspect. Also interesting the oscillscope was still able to decode the signal. Still working on figuring this out.
Pic 1. First test - SCA and SCL connected via pin headers in top left of shield picture above.

Pic 2. Second test - SCA and SCL connected via green TWI port

Pic 3. Clean Signal (no Braccio Shield connection)


texts: How to get version of Arduino board remotely

texts:
I have multiple Arduino WeMos D1 boards, with a mix of versions bought months apart.  One of these boards is working but I need to update it and I am not sure if it is R1 or R2 (the pinouts are different).  I do not have physical access to it (it is 200+ miles away in an area that is locked down) but I can connect through another device over WiFi.
It has the following included:
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

#include <WiFiUdp.h>
#include <ArduinoOTA.h>

So, I can even browse to a Webserver to run commands.  How can I add to the code (or even replace it) to return a value that tells me which version the board is?  According to this you can do it with an AT command, but I am not sure how to pass an AT command from the WebServer interface (or any other way).
EDIT: I guess I may have confused the issue with my phrasing.  I can connect to the board and upload a new sketch (using OTA).  My question is, can I put something in a new sketch to determine the board details and upload it.  Once I get that, I can then put in a the actual sketch that I want.