text:
Loop inside switch statement
I am using voice command to start/stop display of LDR readings over Arduino. The module I am using is voice module V3. I have downloaded some of its examples. First we need to train the module with specific commands. I have trained it as "on" and "off". Hence I could turn on and off the led using voice command .
code:
#include <SoftwareSerial.h>
#include "VoiceRecognitionV3.h"

/**
  Connection
  Arduino    VoiceRecognitionModule
   2   ------->     TX
   3   ------->     RX
*/
VR myVR(2,3);    // 2:RX 3:TX, you can choose your favourite pins.

uint8_t records[7]; // save record
uint8_t buf[64];
int led = 13;

#define onRecord    (0)
#define offRecord   (1)

/**
  @brief   Print signature, if the character is invisible,
           print hexible value instead.
  @param   buf     --> command length
           len     --> number of parameters
*/
void printSignature(uint8_t *buf, int len) {
  int i;
  for(i=0; i<len; i++) {
    if(buf[i]>0x19 && buf[i]<0x7F){
      Serial.write(buf[i]);
    } else {
      Serial.print("[");
      Serial.print(buf[i], HEX);
      Serial.print("]");
    }
  }
}

/**
  @brief   Print signature, if the character is invisible,
           print hexible value instead.
  @param   buf  -->  VR module return value when voice is recognized.
             buf[0]  -->  Group mode(FF: None Group, 0x8n: User, 0x0n:System
             buf[1]  -->  number of record which is recognized.
             buf[2]  -->  Recognizer index(position) value of the recognized record.
             buf[3]  -->  Signature length
             buf[4]~buf[n] --> Signature
*/
void printVR(uint8_t *buf) {
  Serial.println("VR Index\tGroup\tRecordNum\tSignature");
  Serial.print(buf[2], DEC);
  Serial.print("\t\t");
  if(buf[0] == 0xFF) {
    Serial.print("NONE");
  } else if(buf[0]&0x80) {
    Serial.print("UG ");
    Serial.print(buf[0]&(~0x80), DEC);
  } else {
    Serial.print("SG ");
    Serial.print(buf[0], DEC);
  }
  Serial.print("\t");
  Serial.print(buf[1], DEC);
  Serial.print("\t\t");
  if(buf[3]>0){
    printSignature(buf+4, buf[3]);
  } else {
    Serial.print("NONE");
  }
  Serial.println("\r\n");
}

void setup() {
  /** initialize */
  myVR.begin(9600);
  Serial.begin(115200);
  Serial.println("Elechouse Voice Recognition V3 Module\r\nControl LED sample");
  pinMode(led, OUTPUT);
  if(myVR.clear() == 0) {
    Serial.println("Recognizer cleared.");
  } else {
    Serial.println("Not find VoiceRecognitionModule.");
    Serial.println("Please check connection and restart Arduino.");
    while(1);
  }
  if(myVR.load((uint8_t)onRecord) >= 0){
    Serial.println("onRecord loaded");
  }
  if(myVR.load((uint8_t)offRecord) >= 0){
    Serial.println("offRecord loaded");
  }
}

void loop() {
  int ret;
  ret = myVR.recognize(buf, 50);
  if(ret>0) {
    switch(buf[1]) {
      case onRecord:
        /** turn on LED */
        digitalWrite(led, HIGH);
        break;
      case offRecord:
        /** turn off LED*/
        digitalWrite(led, LOW);
        break;
      default:
        Serial.println("Record function undefined");
        break;
    }
    /** voice recognized */
    printVR(buf);
  }
}

The code is running fine. Now to start/stop display on OLED I have included all the necessary OLEd libraries and all and changed the above code only in the switch case as:
void loop() {
  int ret;
  ret = myVR.recognize(buf, 50);
  if(ret>0) {
    switch(buf[1]) {
      case OnRecord:
        display.clearDisplay();
        sensorValue = analogRead(sensorPin);
        display.setCursor(30,0);
        display.setTextSize(1);
        display.print("LDR Reading:");
        display.setCursor(30,10);
        display.setTextSize(2);
        display.print(sensorValue);
        delay(500);
        break;
      case OffRecord:
        display.clearDisplay();
        break;
      default:
        Serial.println("Record function undefined");
        break;
    }
    display.display();
    printVR(buf);
  }
}

Here when I say "on" the OLEd is starting on my voice command. But it remains frozen in the first reading. When I say "off" it turns of the display(as required). The process runs in loop.
I just want to keep on displaying LDR values by running all the statements in "case Onrecord" until case "offrecord" is encountered. Any idea how to do this?
The entire code for the voice controlled LDR readings on OLED is:
#include <SoftwareSerial.h>
#include "VoiceRecognitionV3.h"
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
int sensorPin = A0; // select the input pin for ldr
int sensorValue = 0;

#define OLED_RESET 4
Adafruit_SSD1306 display(OLED_RESET);

 char inChar;
 String string;
/**
  Connection
  Arduino    VoiceRecognitionModule
   2   ------->     TX
   3   ------->     RX
*/
VR myVR(2,3);    // 2:RX 3:TX, you can choose your favourite pins.
uint8_t records[7]; // save record
uint8_t buf[64];

#define OnRecord    (0)
#define OffRecord   (1)

/**
  @brief   Print signature, if the character is invisible,
           print hexable value instead.
  @param   buf     --> command length
           len     --> number of parameters
*/
void printSignature(uint8_t *buf, int len) {
  int i;
  for(i=0; i<len; i++) {
    if(buf[i]>0x19 && buf[i]<0x7F) {
      Serial.write(buf[i]);
    } else {
      Serial.print("[");
      Serial.print(buf[i], HEX);
      Serial.print("]");
    }
  }
}

/**
  @brief   Print signature, if the character is invisible,
           print hexible value instead.
  @param   buf  -->  VR module return value when voice is recognized.
             buf[0]  -->  Group mode(FF: None Group, 0x8n: User, 0x0n:System
             buf[1]  -->  number of record which is recognized.
             buf[2]  -->  Recognizer index(position) value of the recognized record.
             buf[3]  -->  Signature length
             buf[4]~buf[n] --> Signature
*/
void printVR(uint8_t *buf) {
  Serial.println("VR Index\tGroup\tRecordNum\tSignature");
  Serial.print(buf[2], DEC);
  Serial.print("\t\t");
  if(buf[0] == 0xFF) {
    Serial.print("NONE");
  } else if(buf[0]&0x80) {
    Serial.print("UG ");
    Serial.print(buf[0]&(~0x80), DEC);
  } else {
    Serial.print("SG ");
    Serial.print(buf[0], DEC);
  }
  Serial.print("\t");

  Serial.print(buf[1], DEC);
  Serial.print("\t\t");
  if(buf[3]>0) {
    printSignature(buf+4, buf[3]);
  }
  else{
    Serial.print("NONE");
  }
  Serial.println("\r\n");
}

void setup() {
  /** initialize */
  myVR.begin(9600);
  pinMode(13, OUTPUT);
  // initialize with the I2C addr 0x3C / mit I2C-Adresse 0x3c initialisieren
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
  display.display();
  display.clearDisplay();
  display.setTextColor(INVERSE);
  Serial.begin(115200);
  Serial.println("Elechouse Voice Recognition V3 Module\r\nControl LED sample");
  pinMode(sensorPin, INPUT);
  if(myVR.clear() == 0) {
    Serial.println("Recognizer cleared.");
  } else {
    Serial.println("Not find VoiceRecognitionModule.");
    Serial.println("Please check connection and restart Arduino.");
    while(1);
  }
  if(myVR.load((uint8_t)OnRecord) >= 0) {
    Serial.println("startRecord loaded");
  }
  if(myVR.load((uint8_t)OffRecord) >= 0) {
    Serial.println("endRecord loaded");
  }
}

void loop() {
  int ret;
  ret = myVR.recognize(buf, 50);
  if(ret>0) {
    switch(buf[1]) {
      case OnRecord:
        display.clearDisplay();
        sensorValue = analogRead(sensorPin);
        display.setCursor(30,0);
        display.setTextSize(1);
        display.print("LDR Reading:");
        display.setCursor(30,10);
        display.setTextSize(2);
        display.print(sensorValue);
        delay(500);
        break;
      case OffRecord:
        display.clearDisplay();
        break;
      default:
        Serial.println("Record function undefined");
        break;
    }
    display.display();
    printVR(buf);
  }
}

I am able to control the display of LDR readings on OLED using pushbutton. Initially it will be in "off" mode. Once I push the button it starts displaying LDr values in the interval of 500 milli seconds. Once I press the button again, It will clear the display.This will run in a loop.
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
int sensorPin = A0; // select the input pin for ldr
int sensorValue = 0;
bool toggle = false;
int buttonpin;

#define OLED_RESET 4 // not used / nicht genutzt bei diesem Display
Adafruit_SSD1306 display(OLED_RESET);

 char inChar;
 String string;

void setup()   {

  pinMode(13, OUTPUT);

  buttonpin = 2;
  pinMode(buttonpin, INPUT_PULLUP);
  // initialize with the I2C addr 0x3C / mit I2C-Adresse 0x3c initialisieren
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);

  Serial.begin(9600);
  display.display();
  delay(2000);
  display.clearDisplay();

  display.setTextColor(INVERSE);
}

void loop()
{
     if (digitalRead(buttonpin) == HIGH)
     {
      toggle = !toggle;
      while(digitalRead(buttonpin) == HIGH);
     }
      switch( toggle )
         {

          case 1:
           display.clearDisplay();
            sensorValue = analogRead(sensorPin);
            Serial.println(sensorValue);
            display.setCursor(30,0);
            display.setTextSize(1);
            display.print("LDR Reading:");
            display.setCursor(30,10);
            display.setTextSize(2);
            display.print(sensorValue);
            delay(500);

            break;

           case 0:
            display.clearDisplay();

            break;
           }
       display.display();

 }

If you could suggest how I should merge my previous code and the above code so that I could control the display using voice commands, It'll be great!!.
Thanks in advance!

Does the  “freezed in first reading” thing, whatever it might be, happen to last about 500 milliseconds?  What does  “freezed in first reading” mean, exactly?  ¶ Note, “changed the above code only in the switch case” probably is false.  Not showing a  Minimal, Complete, and Verifiable example of code – eg, you don't show declarations of display, sensorValue, and sensorPin, and don't indicate nature of sensor or model of OLED –  makes it difficult to diagnose problems.

I mean to say that the OLED displays one LDR reading taken at the moment I say "on". And the display doesnt refresh to give continuous LDR reading . Eg : the OLED shows " LDR Reading :372"  This will remain on the screen as it is until I say "off" which clears the display and make it blank. Then again when I say "on" , it displays another reading taken at the moment and it remains as it is on screen. I want the OLED to display continuous readings at an interval of 500 milli seconds and should clear the display once I say "off".  I am uploading the full code.

For debugging, add a Serial.print() or and/or an OLED output (on a different line) that every half second or so tells the current sensor reading and the most-recent voice-unit output.  Or temporarily add a button to simulate an On event.  Do you know for sure that the sensor reading should change?  Or does the OLED obviously blink each time a reading is put up?  Do you know if an  On event is occurring after the first On, or if it is a display issue?

I am just trying to print the analog values (example from basic arduino). Here I am getting analog values and I am trying to print the same on OLED. Without voice module , I am able to get the LDR readings on OLED. Now after adding the voice command, my statement is isnide switch case followed by break. I am able to verify whether my voice command is recorded or not from serial monitor. The problem is with code. The display should run in a loop showing LDR values after half second. The code is the problem.

But it remains frozen in the first reading.

because in the next run of loop(), the "ret = myVR.recognize(buf, 50);" returns a value of 0 -> no voice command is recognized.
the way to do it is to have a state machine like this:
  ret = myVR.recognize(buf, 50);  //read the voice command
  switch(buf[1]) {
      case OnRecord:
        if (vr_state == OffRecord) vr_state = OnRecord; //from previous off to on now
        break;
      case OffRecord:
        vr_state = OffRecord; //now to be off
        break;
      default:
        break; //do nothing -> keep status quo
  }
  //process vr_state
  switch (vr_state) ...

basically, there is potentially information even if no voice command is received (aka. previously OnRecord and now silence). your code's reaction to "ret" is dependent on its value now and its value previously.

To keep reading and reporting a sensor within loop() after each On command, until an Off command occurs, add a flag variable – eg, tellSensor – to control that reading and reporting.  Declare the variable outside loop(), or declare it static within loop(), and initialize it false.
In the code for case OnRecord:, initialize the display (eg, clear display and print the LDR Reading: heading) and set  tellSensor true.
In the code for case OffRecord:, clear the display and set  tellSensor false.
After the end of the if(ret>0) { ... } if statement, say something like
if (tellSensor) {
   display.setCursor(30,10);
   display.setTextSize(2);
   display.print(sensorValue);
   delay(500);
}

I tried your solution. I initialized static bool Tellsensor= False in loop. Modified case OnRecord and OffRecord as you said. And after if(ret>0){..}.. added the if statement. But the results where same , the loop does not run when I say "On". It displays first reading and remains as it is. Once I say "off" it turns off the display. I tried moving the same if statement within if(ret>0){..} and here when I say "on" it displays one reading , again by saying "on" it refreshes and prints the next reading. By saying "off" the display goes blank. Any idea how to fix this?

By "static bool Tellsensor= False in loop", are you referring to a declaration and initialization right at the beginning of loop(), or some other loop?  It should be the former.  But the symptom sounds like it isn't.  Anyway, for testing I'd move its  declaration and initialization to global.  Note, I'll be away a few days.


text:
HC-06 pairing to arduino
I have a bluetooth module HC-06 and want to pair it to my Arduino UNO. The thing is when I researched how to do so, I got different answers. What pairing should I use? Thank you in advance. I have highlighted the differences.
First version:
https://www.instructables.com/id/Add-bluetooth-to-your-Arduino-project-ArduinoHC-06/
HC-06>>>Arduino
VCC>>>>3.3v
GND>>>>GND
TXD>>>>RXD
RXD>>>>TXD
Second version:
http://42bots.com/tutorials/hc-06-bluetooth-module-datasheet-and-configuration-with-arduino/
HC-06            <<>> Arduino
HC-06 Ground GND <<>> GND
HC-06 VCC pin  <<>> 5v
HC-06 TX/TXD pin <<>> Arduino RX
HC-06 RX/RXD pin << resistors >> Arduino TX
[![enter image description here][1]][1]
[![enter image description here][2]][2]

Which you use depends on two factors: the HC-06 carrier board you have, and which Arduino you are using.
If your carrier board has (and most do) a 3.3V regulator then you power the board from 5V.
If your Arduino is a 5V Arduino (such as an Uno) then you need a voltage divider on the (arduino)TX->(hc)RX pins otherwise you risk damaging the bluetooth module.

Thanks. How can I tell the carrier board of the HC-06 only by looking at the device itself. I have no manuals or other information about it.

@B.Parvi Post a picture.

@B.Parvi Ok, that's one of the normal cheap eBay carriers. Yes, it has a voltage regulator. Give it 5V on Vcc.

source: Stack Exchange

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

sort: votes


text:
SD card failed to initialize
I have a Pro Micro board and I try to make it list my files as in the example of the Arduino IDE.
The pins I use are the following:
board    micro sd module
   D4  ---> CS
   D15 ---> SCK
   D14 ---> MISO
   D16 ---> MOSI
   GND ---> GND
   VCC ---> VCC

On the serial monitor I get "initiallization failed".
What is wrong with my setup?
This is the code running:
#include <SPI.h>
#include <SD.h>

File root;

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

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

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

  root = SD.open("/");

  printDirectory(root, 0);

  Serial.println("done!");
}

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

void printDirectory(File dir, int numTabs) {
  while (true) {

    File entry =  dir.openNextFile();
    if (! entry) {
      // no more files
      break;
    }
    for (uint8_t i = 0; i < numTabs; i++) {
      Serial.print('\t');
    }
    Serial.print(entry.name());
    if (entry.isDirectory()) {
      Serial.println("/");
      printDirectory(entry, numTabs + 1);
    } else {
      // files have sizes, directories do not
      Serial.print("\t\t");
      Serial.println(entry.size(), DEC);
    }
    entry.close();
  }
}

And this is my wiring:

Please add your code.

maybe your program consists of only these two commands ..... Serial.begin(9600);  Serial.println("initiallization failed");  ..... that would give you the observed output

did you insert the card?

what are the voltages of board and SD module?

@jsotola I study computer science man, this is not one of my possible mistakes. But thank you for your comment

@Juraj Yes I inserted the card. How can I see the voltages?

in specification. pro micro's are 5 V or 3.3V. SD card modules are with voltage conversion to 5 V or only a holder for SD card with 3.3V native voltage

So the voltages are ok? I connect it to my pc via usb. How can I look further to this? I am sure it should have worked by now.

@MichelKeijzers I did, any guesses?

connection to USB doesn't say anything about voltages. add links to where you bought them, if you don't know the specs

I bought both the board and the module a long time ago from Ebay. The module is from Catalex and says v1.0. My sd card is a standard one (Kingston 4gb) and the module is probably the cheapest pro micro on ebay.

Catalex SD module is 5 V. On pro micro you could measure a voltage of an OUTPUT HIGH pin

How do I do this?

is the SD card formatted to FAT or FAT32?

I am not sure. Could this be the problem?

that would be definitely the problem. put the card in a computer and check it

it was ntfs I am sure, I am formating it to FAT now. But this should be a problem at software level, doesn't it? Due to my sketch it seems that it fails to init

do you have a voltmeter/multimeter to measure voltage of vcc or a pin?

No, not yet. I have ordered a multimeter but it has not arrived yet

is something written on the bottom side of the pro micro?

Let us continue this discussion in chat.

I only would think of inserting the SD card, using a FAT (not NTFS) formatted card, and optionally try another SD card (got problems myself depending on the SD Card). Also I would advice buying a (around 5$) logic analyzer from Ebay, than you can relatively easy find out what's going over the jumper wires.

@MichelKeijzers, read the chat finale

The SD library works only with FAT and FAT32 format. SD.begin() reads the 'disc volumes' and opens the root folder. If the card is not formatted or formatted with other file system standard, begin() fails.
EDIT: and the pin headers must be soldered

Yea, I got it. I just formated it to FAT32 and it didnt work either. What else could it be?

Here's my setup code for my SD card for a little circuit where I was writing temperature data to the card.
const int SD_CS = 10;
   const long SLEEP_TIME = 60000;  // write to card every minute
   long multiplier = 0;

   LiquidCrystal_I2C lcd(0x3F, 20, 4);

   void setup() {

     lcd.begin();
     lcd.setCursor(2,0);
     lcd.print("Hello, LCD!");

     if (SD.begin(SD_CS)) { // init SD
       lcd.setCursor(2,2);
       lcd.print("SD card init");
     }

 }

I set the CS pin to D10.
Try switching it to another pin like this and see if you get a different result.  I believe I had a challenge when I used pin 4 but can't quite remember.
Note: And of course remember to move your CS wire to pin D10 or whichever one you use.

the problem is revealed in chat

@Juraj Headers not soldered! Yipes! I asked a relevant question about this long ago -- https://electronics.stackexchange.com/questions/249140/how-can-i-make-connection-on-pcb-circuit-board-holes-without-solder-for-proto
Great catch!

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


text:
SPI Problem with K-Thermocouple and Potentiometer?
I have a setup where the Arduino reads input from the k-thermocouple and uses that info to regultate the an output voltage through a potentiometer. I know the potentiometer is not faulty because able to read the output from the wiper when I run the program but for some reason, k-thermocouple is stuck at 0 Celsius. I know that the k-thermocouple is not faulty either because it works accordingly when I run a program specifically by itself.
Does anybody know why there is a problem with how the k-thermocouple is operating in junction with the potentiometer? Here is a declarations of my program.
#include <SPI.h>

// K-couple dependent DigiPot Regulator

#include "SPI.h"
#include "max6675.h"

byte address = 0x10;
int CLK = 13;
int CS = 10;
int SDI = 11;
const int ktcSO = 12;
int ktcCS = 9;
int ktcCLK = 13;

MAX6675 ktc(ktcCLK, ktcCS, ktcSO);

int digitalPotWrite(int value) //Everything that happens when the DigiPot is
called
{
  digitalWrite(CS, LOW); // Chip Select is ACTIVE LOW (so now it's selected)
  SPI.transfer(address);
  SPI.transfer(value);
  digitalWrite(CS, HIGH);
}

void setup()
{
  SPI.begin();
  pinMode (CLK, OUTPUT);
  pinMode (CS, OUTPUT);
  pinMode (SDI, OUTPUT);
  Serial.begin(9600);
  // give the MAX a little time to settle
  delay(500);
}

void loop()
{
  if (ktc.readFahrenheit() < 60)  // While it's still in Safe Zone
  {
    digitalPotWrite(255);
    // Show the current temp in C and F
    Serial.print("Deg C = ");
    Serial.print(ktc.readCelsius());
    Serial.print("\t Deg F = ");
    Serial.print(ktc.readFahrenheit());
    int sensorValue = analogRead(A0);
    float voltage = sensorValue * (5.0 / 1023.0);
    Serial.print("\t V = ");
    Serial.println(voltage);
    int clockValue = analogRead(A1);
    Serial.print("\t Clock = ");
    Serial.println(clockValue);
  }
        if (ktc.readFahrenheit() < 65) // While in Caution Zone
        digitalPotWrite(51);
        else if (ktc.readFahrenheit() < 70)
        digitalPotWrite(102);
        else if (ktc.readFahrenheit() < 75)
        digitalPotWrite(153);
        else if (ktc.readFahrenheit() < 78)
        digitalPotWrite(184);
        else if (ktc.readFahrenheit() < 80) //Getting into Danger Zone
        digitalPotWrite(204);
        else if (ktc.readFahrenheit() < 81)
        digitalPotWrite(214);
        else if (ktc.readFahrenheit() < 82)
        digitalPotWrite(224);
        else if (ktc.readFahrenheit() < 83)
        digitalPotWrite(235);
        else if (ktc.readFahrenheit() < 84)
        digitalPotWrite(245);
        else (ktc.readFahrenheit() < 85); //Complete Shutoff
        digitalPotWrite(255);
    {
     Serial.print("Deg C = ");
     Serial.print(ktc.readCelsius());
     Serial.print("\t Deg F = ");
     Serial.print(ktc.readFahrenheit());
     int sensorValue = analogRead(A0);
     float voltage = sensorValue * (5.0 / 1023.0);
     Serial.print("\t V = ");
     Serial.println(voltage);
     int clockValue = analogRead(A1);
     Serial.print("\t Clock = ");
     Serial.println(clockValue);
    }
}

Also, the code I used to test the K-Thermocouple is one that can be found on the internet (with just a little bit of adjustments)...
// Sample Arduino MAX6675 Arduino Sketch

#include "max6675.h"

int ktcSO = 12;
int ktcCS = 9;
int ktcCLK = 13;

MAX6675 ktc(ktcCLK, ktcCS, ktcSO);

void setup() {
  Serial.begin(9600);
  // give the MAX a little time to settle
  delay(500);
}

void loop() {
  // basic readout test

   Serial.print("Deg C = ");
   Serial.print(ktc.readCelsius());
   Serial.print("\t Deg F = ");
   Serial.println(ktc.readFahrenheit());
   int clockValue = analogRead(A1);
    Serial.print("\t Clock = ");
    Serial.println(clockValue);

   delay(500);
}

Please edit your question to include a circuit diagram.  Which lines do you have pullups on? What do you have connected to MISO, dig. pin 12?  Do you have an oscilloscope to check the clock signal during temperature reads, or to check data bits at MISO during reads?

Yes, I have MISO connected to pin 12. When I run a program to test the K-Thermocouple itself, I do get a square wave clock signal on the oscilloscope but then when I run the program above, the clock signal is indiscernible. It looks like a complete noise.

What's attached to A1?  Why is clockValue reading differently in the two sketches?

I think that may be the cause of my problem. When I had it hooked up to an oscilloscope, I was getting a pulse wave for the first one but the second one was complete static and indiscernible. This is what leads me to believe that the issue is rooted from the CLK signal of SPI with both the K-Thermocouple and the DigiPot in conjunction.

The wiring diagram, if accurate, shows a couple of problems.
First, A0 has nothing attached to it, so sensorValue may read in as zero or some small random number.
Second, attaching the digital pot's analog output pin 6, P1W, to the Uno's digital input pin 12 is pointless.  Instead connect P1W to whatever it is supposed to control.  If you want to handle data from the MCP42X1, connect its pin 13, SDO, to an Uno input.
However, neither of those problems appears to be related to misreading the MAX6675 temperature.  I don't know of a good approach to solving that problem, but if I were working with the circuit, would remove the wire between P1W and the Uno's digital pin 12, and would use 12 as the input from the MAX6675; that is, would wire it to d12 instead of d8, and instead of int ktcSO = 8 would say const int ktcSO = 12.  Also, I'd probably replace the bit of code
  }
  else
  {
    while (ktc.readFahrenheit() < 85)
      {

with just a closing }.  In the Arduino paradigm, loop() runs repeatedly, and the if–else sequence adequately guards each of the digitalPotWrite() calls.
Note, the digitalPotWrite() function should be defined or declared before any calls to it appear.  Instead of placing that function at the end, put it before  loop() or before setup().

My mistake on the A0. I originally had it there and switched it to D12 sometime during my troubleshooting process.
One question tho... I'm assuming your're saying I should replace the highlighted portion with
"}  loop()"
but wouldn't the program get stuck in loop the moment it enters it?

Looks like I read it wrong. No additional loop.

jwpat7 So I've applied all the changes that you suggested and the MAX6675 is still not registering any input. Side note: I have P1W connected to A0 so that I can monitor my output and also don't pay any mind to Vdd and Vss. I have them correctly connected in my circuit.

I added a few lines of code to try and show the clock signals (D13 <--> pin 2) of the MAX6675 when tested by itself and the whole circuit. There is some form of signal output every loop for the MAX6675 test itself but there is no signal when tested for the whole circuit.

The reason for replacing those five lines of code is that (1) your program will get stuck in the while (ktc.readFahrenheit() < 85) loop if readFahrenheit() isn't working or if you aren't changing the temperature at the sensor.  If it's stuck in that while loop, it won't produce any output.  And (2), decoupling the rest of loop() from its first 15 lines simplifies figuring out what it is doing.

I don't get exactly what you mean by  “some form of signal output every loop for the MAX6675 test itself but there is no signal when tested for the whole circuit” – in particular, it isn't clear to me whether your  “MAX6675 test itself” just loads and runs a specialized MAX6675-testing sketch, leaving the wiring as is, or whether you change just the hardware, or if you change both.  Given my lack of understanding of that, I don't know if you should be looking for a hardware issue or software.  Does all the hardware work ok if you run specialized test sketches, leaving the wiring as is?

Yes, that's exactly what is it. I ran a specialized testing sketch for the MAX6675 alone with the wiring as is and it works just fine. That's what the first side of the result picture shows. The right side is the output of the whole circuit. I added a few lines of code to print out the clock signal (value) during each loop since I don't have an oscilloscope at hand at the moment and I don't know how else to display the Serial CLK through my Arduino IDE.

I didn't see those outputs when I was editing my answer.  Anyhow, if you add the exact code for the left side output, and the exact code for the right side output to the question, I'll look at the code again.  Can you update the circuit diagram to match what you have, with A0 connection fixed?

I updated the circuit diagram and included the changes suggested in the main code as well as including the code used to test the K-Thermocouple.

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


text:
How to change colors and theme settings in 'Windows Store app' version of Arduino IDE?
In the standard Windows (Win32) version of the Arduino IDE, theme settings like syntax coloring can be modified in C:\Program Files (x86)\Arduino\lib\theme\theme.txt.
For the Windows Store app version of the IDE the theme files are stored in protected app storage space.
Is there a simple/safe way to change theme settings for the Windows Store app version of the IDE without messing up security settings and inadvertently lowering Windows security?
(It would be easier and better if theme settings could be moved to the ArduinoData user folder where preferences.txt is stored.)

Don't use the Windows App Store version?

I assume not using the Windows Store version is not an option (because that's the easiest answer).  An alternative that might work (if you have admin access) is to use Junction.exe to create a symbolic link between a writeable directory and where the themes are stored. But changing the perms on that directory is going to be easier.

Working from what Ignacio Soler Garcia wrote (which didn't work for me), I tried around and came up with a solution for my case (I downloaded the OneDarkArduino Theme from GitHub):

Unpack the theme if it came in a ZIP file
copy the folder called "theme" (there should be a bunch of .txt and .svg files in there)
paste it into the folder where all your projects are (usually something like C:\User\Documents\Arduino) - it needs to be named "theme"
(re)start the Arduino IDE and now it should start with the new theme already loaded

I think rrz0's answer skipped the part of the question:
"For the Windows Store app version of the IDE the theme files are stored in protected app storage space."
The only way is to take control of the windows app folder but I believe this is risky and M$ suggests that this can brick your pc (take that with a grain of salt).
There is an offline windows installer and zip link on the downloads page which I used to replace the windows store version. I see no advantage to the store version.

I can confirm that changing ownership/security on the WindowsApps folder half-bricked my machine... it still ran classic windows but every single store App wouldn't run and the store itself stopped working... and I couldn't reset the security back again - 4 hours later and a complete restore with Microsoft's recovery download and a 16GB USB boot load , I'm older and wiser.

There is a way, but not necessarily simple. You basically need to replace the current theme files with the new ones.

Rename {Arduino IDE installation folder}/lib/theme to {Arduino IDE installation folder}/lib/theme.bak
Download https://github.com/jeffThompson/DarkArduinoTheme/archive/master.zip
Copy the theme folder from the downloaded file to {Arduino IDE installation folder}/lib
Restart the Arduino IDE if it's running.

I found the solution, based on a new functionality for themes that I wasn't aware of.
You need to create a themes folder in the folder where your projects are (the one that appears in the preferences section) and put inside it the theme in a zip file. After restarting it will appear as a new theme in the combobox themes.

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


text:
Powering an Arduino with more than 5 V
Last time, when I supplied 12 V from a power supply to the Arduino's 5V pin, it blew up. This time I'm going to use an adapter. Why does an adapter with a 12 V input not blow an Arduino up, as in the previous case?
Or, should I have supplied 12 V to Vin pin, instead of the 5 V pin?
Edit: Sorry for saying 12V input, it is written 12V output and I meant a power adapter that is plugged into wall.

What sort of adapter are you talking about? Do you mean a power adapter that you plug into the wall, to convert 240 V a.c. mains electricity to 5 V d.c.? Apparently you aren't referring to a power adapter, as you say that the adapter has a 12 volt input, so do you mean a DC-DC convertor? Or do you mean a regulator, that reduces voltage from 12 volts to 5 volts (which, effectively, does the same as a DC-DC convertor)? Please edit your question to clarify.

Congratulations on confirming their design.  That is exactly what it is supposed to do.  When you feed more than 5V into the 5V pin it is specifically designed to melt down and never work again.  I bend the pins inward to show they are n/w then give them to the kids to play with.
Sometimes I turn up a few pins like they are eyes or horns.  It makes a fun toy.  Meanwhile, you have now discovered why they provide the Vin pin, which goes through a regulator.  With that pin, 9-12 volts is just fine.

12 Volts is fine into the barrel connector.

First of all you should read the tech specs for Arduino Uno here:
https://www.arduino.cc/en/Main/ArduinoBoardUno
You will find this important information about power supply:
Operating Voltage   5V
Input Voltage (recommended) 7-12V
Input Voltage (limit)   6-20V

From documentation also:
Vin. The input voltage to the Arduino/Genuino board when it's using an external power source (as opposed to 5 volts from the USB connection or other regulated power source). You can supply voltage through this pin, or, if supplying voltage via the power jack, access it through this pin.
5V pin.This pin outputs a regulated 5V from the regulator on the board. The board can be supplied with power either from the DC power jack (7 - 12V), the USB connector (5V), or the VIN pin of the board (7-12V). Supplying voltage via the 5V or 3.3V pins bypasses the regulator, and can damage your board. We don't advise it.
So answering you question: yes you should have supplied 12v on Vin. Not on 5v.

Why does an adapter with 12V input not make the same blown up for arduino like in the previous case?

Because you are pluging 12v in the correct input, the 7-12v jack.
Another important link to read:
http://playground.arduino.cc/Learning/WhatAdapter


text:
Can you connect more sensors of the same type to a single board while not using up more pins than if you were to use a single sensor?
I'm as new as you can be at Arduino programming and specific electronics, so I don't even know if I'm asking the correct question.
I've ordered an Arduino a breadboard and some PCBs and now I'm looking for a few parts that I should buy in order to get some basic projects done.
I'd like to start with a garden automation project, a fairly simple one.
Humidity sensors, temperature sensors and a water pump.
Can I connect all (4) of the humidity sensors to a single local circuit and then connect that to the board so I can limit the number of input pins used? I'd still need to get independent readings from the sensors. Or would I need to use another board incorporating RF/Wireless/Bluetooth modules to receive the information and then send it to the board for further processing?
I'm sorry if what I just said makes no sense and I thank you for your time.
All I have is low-mid level electronic related experience. Battery checkers, Power supplies, basic light sensors, PCB making ETC.

Did any of the answers help? If so, please accept the answer that helped. If not, please post your own answer and mark it as accepted in 48 hours time. Thank you.

If the connection is a digital sense pin then you can use a parallel-in serial-out IC to read them all simultaneously and then shift it in. Takes up 3 pins on the arduino a latch a clock and a data pin.
If the connection is SPI then you can connect the clocks and MISO pins together and then need a slave select for each. you can control many of them with a serial in parallel out IC or a decoder.
If the connection is with the I2C protocol and each device has a different address then you can simply connect them all in parallel.
If the sensor has an analog output then you can use an analog to digital converter (ADC) which can have multiple inputs and often have a serial interface.

It all depends on the interface between the Arduino and the sensor.
For example the DS18B20 uses the 1-Wire bus. That requires one digital pin and a number of DS18B20 can be connected to the same 1-Wire bus. Every DS18B20 has an unique identifier that makes that possible.
Humidity sensors like DHT11 or DHT22 require a pin for each sensors. They are not accurate anyway.
Sensors like the BME280 use the I2C bus. The I2C bus allows that many sensors can be connected. Each I2C sensor has an I2C address. Sometimes a sensor can have just one I2C address and therefor only one of such a sensor can be connected to the I2C bus. But sometimes a trick is possible to have more.
This list goes on and on and on. A lot is possible without extra hardware.
Because you are going to use sensors and many sensors are 3.3V, did you buy a 3.3V Arduino board ?

If you do not need them to run simultaneously, you can use a multiplexer such as this one from Sparkfun:
https://www.sparkfun.com/products/9056

This doesn't look like a question, it looks like an answer.


text:
Wemos D1 mini with relay shield (why does D1 not operate relay but D5 does)?
I connect gnd>gnd, 5v>5v and d1>d1 - nothing works with relay blink code
I change connection to d5 on wemos (still d1 on relay) and it works fine with code change to d5
Any ideas, as at present I can't stack the relay on the wemos? (because the d1 goes to d1)
According to pinout, D1 is "I/O, in the default mode, SCL of I2C" and GPIO5.
Thanks
Code:
/*
 * Relay Shield - Blink
 * Turns on the relay for two seconds, then off for two seconds, repeatedly.
 *
 * Relay Shield transistor closes relay when D1 is HIGH
 */

const int relayPin = D1;
const long interval = 2000;  // pause for two seconds

void setup() {
  pinMode(relayPin, OUTPUT);
}

void loop() {
  digitalWrite(relayPin, HIGH); // turn on relay with voltage HIGH
  delay(interval);              // pause
  digitalWrite(relayPin, LOW);  // turn off relay with voltage LOW
  delay(interval);              // pause
}

Also on GitHub.
Wemos D1 mini:
https://www.amazon.co.uk/gp/product/B071S8MWTY/ref=oh_aui_detailpage_o00_s01?ie=UTF8&psc=1
5V relay:
https://www.amazon.co.uk/gp/product/B07DK1FZF9/ref=od_aui_detailpages00?ie=UTF8&psc=1

post your code directly in the question.  It helps others search for your post on SE

D1 is io 5. the labels on the board have constants in code but the real io pin numers are different. if you use 5 it is D1. if you use D5 it is io 14. D1 is I2C only if you use the Wire library. the shield uses only one pin. you can't choose which one


text:
expected unqualified id-before '/' token ------ can someone help, please
/* Multiple State Handling
* 05-22-2019
*/

#define button 3                        //Push button on D3
#define lowbeam 5                       //Low Beam on D5
#define highbeam 6                      //High Beam on D6
#define gate 7                          //Gate on D7

/------------------------------------------------------------------------

int state = 0;                          //integer to hold current state
int old = 0;                            //integer to hold last state
int buttonPoll = 0;                     //integer to hold button state
/-------------------------------------------------------------------------

void setup() {
  pinMode(button,INPUT);                //button set as input
  pinMode(lowbeam,OUTPUT);              //relays set as outputs
  pinMode(highbeam,OUTPUT);
  pinMode(gate,OUTPUT);

  digitalWrite(lowbeam,LOW);            //initial state as off
  digitalWrite(highbeam,LOW);           //initial state as off
  digitalWrite(gate,LOW);               //initial state as off

}
/-------------------------------------------------------------------------
void loop() {

                                        //debouncing routine to read button
  buttonPoll = digitalRead(button);     //poll state of button
  if(buttonPoll == 1){                  //check if it has been pressed
    delay(50);                          //wait 50msec
    buttonPoll = digitalRead(button);   //poll button again
    if(buttonPoll == 0){                //if it is 0 consider 1 press
      state = old +1;                   //increase state by 1
    }}
  else{                                 //if button has not been pressed
  deley(100);                           //wait 100ms
  }
  switch (state) {                      //react to button press & state
    case 1:                             //if state is 1
      digitalWrite(lowbeam,HIGH);       //lowbeam relay on
      digitalWrite(highbeam,LOW);       //highbeam relay off
      digitalWrite(gate,LOW);
      old = state;                      //set old state as current state
      break;
    case 2:
      digitalWrite(lowbeam,LOW);
      digitalWrite(highbeam,HIGH);
      digitalWrite(gate,LOW);
      old = state;
      break;
    case 3:
      digitalWrite(lowbeam,LOW);
      digitalWrite(highbeam,LOW);
      digitalWrite(gate,HIGH);
      old = state;
      break;
    default:                            //if state if no 1,2,3
      digitalWrite(lowbeam,LOW);        //all relays off
      digitalWrite(highbeam,LOW);
      digitalWrite(gate,LOW);
      old = 0;                          //reset to all off/state 0
      break;
  }
}

Usually the debugger tells you on which line of the program the error is located...

OK, you just had a couple of minor typos.
It's nice to break up your code for readability, but single-line comments comments start with a double slash //, rather than a single.
Also, you had mis-spelled 'delay' in your loop.

This should compile without errors:
/* Multiple State Handling
* 05-22-2019
*/

#define button 3                        //Push button on D3
#define lowbeam 5                       //Low Beam on D5
#define highbeam 6                      //High Beam on D6
#define gate 7                          //Gate on D7

//------------------------------------------------------------------------

int state = 0;                          //integer to hold current state
int old = 0;                            //integer to hold last state
int buttonPoll = 0;                     //integer to hold button state
//-------------------------------------------------------------------------

void setup() {
  pinMode(button,INPUT);                //button set as input
  pinMode(lowbeam,OUTPUT);              //relays set as outputs
  pinMode(highbeam,OUTPUT);
  pinMode(gate,OUTPUT);

  digitalWrite(lowbeam,LOW);            //initial state as off
  digitalWrite(highbeam,LOW);           //initial state as off
  digitalWrite(gate,LOW);               //initial state as off

}
//-------------------------------------------------------------------------
void loop() {

                                        //debouncing routine to read button
  buttonPoll = digitalRead(button);     //poll state of button
  if(buttonPoll == 1){                  //check if it has been pressed
    delay(50);                          //wait 50msec
    buttonPoll = digitalRead(button);   //poll button again
    if(buttonPoll == 0){                //if it is 0 consider 1 press
      state = old +1;                   //increase state by 1
    }}
  else{                                 //if button has not been pressed
  delay(100);                           //wait 100ms
  }
  switch (state) {                      //react to button press & state
    case 1:                             //if state is 1
      digitalWrite(lowbeam,HIGH);       //lowbeam relay on
      digitalWrite(highbeam,LOW);       //highbeam relay off
      digitalWrite(gate,LOW);
      old = state;                      //set old state as current state
      break;
    case 2:
      digitalWrite(lowbeam,LOW);
      digitalWrite(highbeam,HIGH);
      digitalWrite(gate,LOW);
      old = state;
      break;
    case 3:
      digitalWrite(lowbeam,LOW);
      digitalWrite(highbeam,LOW);
      digitalWrite(gate,HIGH);
      old = state;
      break;
    default:                            //if state if no 1,2,3
      digitalWrite(lowbeam,LOW);        //all relays off
      digitalWrite(highbeam,LOW);
      digitalWrite(gate,LOW);
      old = 0;                          //reset to all off/state 0
      break;
  }
}


text:
Fedora 36 cannot find TTGO32 arduino board
I've been trying to solve this problem for a while now. Fedora 36 cannot recognise my arduino board. Well, not correctly at least.
Arduino IDE v2 picks it up as ttyS4, but platformio only has an empty list for "pio device list".
In addition, "dmesg -w" and any other variation of it doesn't see any new USB devices, even if they do work.
I've tried installing the independent drivers to no avail. I bought a new board to make sure it's not a fried board. I also checked quite a number of USB cables, but still be problem persists.
Finally, I made sure to only use a fresh install of Fedora 36 but still no luck.
Has anyone here had similar problems before and if so any advice on how to get this sorted out? I'm currently using a laptop.

If there is nothing in dmesg -w when you plug the board in then it sounds like you're not using a proper USB data cable but a USB charger cable.

That actually makes a lot of sense... I'll see if I can scavange some more cables and test them as well.

It seems like I did indeed choose the wrong cable. Thank you for your help!


text:
ESP_ATMod and its many library dependencies
I'm trying to install https://github.com/JiriBilek/ESP_ATMod onto an ESP8266. The sketch has Includes to many libraries. Those libraries have includes to other libraries and so on. Do I have to manually follow all these dependencies and download them to compile and upload my sketch? Or is there an easier way.

An Arduino sketch is a folder not a file. The ESP_ATMod sketch has 11 files:
asnDecode.cpp
asnDecode.h
command.cpp
command.h
debug.h
ESP_ATMod.h
ESP_ATMod.ino
settings.cpp
settings.h
WifiEvents.cpp
WifiEvents.h

The sketch doesn't include libraries which would require installation. It uses only libraries bundled with the esp8266 platform: EEPROM, ESP8266mDNS, ESP8266WiFi and LittleFS. You don't have to install any libraries.
You can download all the files at once with "Download ZIP":

Ah my mistake was not to set the board to ESP8266, it was still set to Arduino. The dependency error has now gone.


text:
Code not checking for updated sensor values after connecting to firebase?
I am using a project with an MQ138 sensor and want to push the real time sensor reads to firebase. Currently, the wifi/firebase part and sensor part work fine separately. The code connects to wifi and will update a temporary variable (just an int that gets 1 added to it every time the loop runs) and put that on firebase. On a separate arduino file, the code is also able to read the sensor, do math with it, and consistently update. However, when I put the two together and try to print the sensor output, the value does not change at all (both the raw analogRead AND the raw value after being put through some math)--even when it does change on the separate code I ran without any firebase/wifi involved.
Why is this? Could there be some sort of cache that saves the old sensor value? Something with the way the code loops? The only different between the firebase code and the sensor test code (without use of firebase) is that on the Arduino software the board has to be selected as ESP8266 for firebase/wifi connection to work, but the test code uses Arduino Uno as a board. Could there be something with this that is not letting AnalogRead (for the sensor) work properly?
The circuit is wired so that the ESP8266 and MQ138 sensor are both connected to an Arduino Uno.
My code is below (currently, the sensor output is only getting printed in serial, and the integer "n" is consistently getting updated and pushed on firebase, but even the serial output of the sensor won't change):
#include <Firebase.h>
#include <FirebaseArduino.h>
#include <FirebaseCloudMessaging.h>
#include <FirebaseError.h>
#include <FirebaseHttpClient.h>
#include <FirebaseObject.h>
#include <dummy.h>

#include <ESP8266WiFi.h>
#include <FirebaseArduino.h>
#include <SPI.h>
#include <Wire.h>
#include <DHT.h>
#include <Adafruit_BMP085.h>

//passwords have been removed, but are in the actual code
#define FIREBASE_HOST ""
#define FIREBASE_AUTH ""

#define WIFI_SSID ""
#define WIFI_PASSWORD ""

//Hardware Macros for sensor
#define MQ138 (5) //Analog 5 input
#define RL_VALUE (10000) //Load resistance in ohms
//Software macros
#define         CALIBRATION_SAMPLE_TIMES     (40)    //define how many samples you are going to take in the calibration phase
#define         CALIBRATION_SAMPLE_INTERVAL  (500)   //define the time interal(in milisecond) between each samples in the
//cablibration phase
#define         READ_SAMPLE_INTERVAL         (50)    //define how many samples you are going to take in normal operation
#define         READ_SAMPLE_TIMES            (5)     //define the time interal(in milisecond) between each samples in

//Globals for math with the sensor
float AcetoneCurve[2] = {3.720, -2.222}; //A, B
float R0 = 10000; //Initialized to 10k ohms
unsigned long SLEEP_TIME = 600; // Sleep time between reads (in seconds)
int val = 0;          // variable to store the value coming from the sensor
float calcVoltage = 0;
float dustDensity = 0;
boolean metric = true;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  Serial.print("help");
  WiFi.disconnect();
  Serial.setDebugOutput(true);
  /*IPAddress ip(192,168,3,34);
  IPAddress gateway(192,168,3,1);
  IPAddress subnet(255,255,255,0);*/
  WiFi.setAutoReconnect(true);

  //connect to Wifi
  WiFi.mode(WIFI_STA);
  WiFi.hostname("ESP-host");
  //WiFi.config(ip, gateway, subnet);
  WiFi.enableInsecureWEP(true);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("connecting");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    Serial.print("Wifi status: ");
    Serial.println(WiFi.status());
    delay(500);
  }
  Serial.println();
  Serial.print("connected: ");
  Serial.println(WiFi.localIP());
  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);

  //define pin
  pinMode(MQ138, INPUT);
}

int n = 0;

void loop() {
  // put your main code here, to run repeatedly:
  //MQ138 code
  int raw = analogRead(MQ138);
  static float Ro = MQCalibration(MQ138, 25, RL_VALUE, AcetoneCurve);    //Assuming 25ppm of acetone in clean air?
  float Rs = MQRead(MQ138, RL_VALUE);
  float ratio = Rs / Ro;
  int ppm = MQGetPercentage(ratio, Ro, AcetoneCurve);

 //This prints the same output every time, even when it shouldn't
  Serial.println(raw);
  Serial.print("PPM: ");
  Serial.println(ppm);

//Firebase code
  // set value
  Firebase.setFloat("PPM", n);
  //error catching
  if (Firebase.failed()) {
    Serial.print("setting /number failed:");
    Serial.println(Firebase.error());
    return;
  }
  delay(1000);
  // appending a new value to /logs, CHANGE INT
  String name = Firebase.pushInt("logs", n++);
  //handle error
  if (Firebase.failed()) {
    Serial.print("pushing /logs failed: ");
    Serial.println(Firebase.error());
    return;
  }
  Serial.print("pushed: /logs/");
  Serial.println(name);
  delay(1000);

  if (Firebase.failed()) {
    return;
  }

}

//Functions - for calculating the PPM from a raw sensor reading, can be ignored
/****************** MQResistanceCalculation ****************************************
  Input:   raw_adc - raw value read from adc, which represents the voltage
  Output:  the calculated sensor resistance
  Remarks: The sensor and the load resistor forms a voltage divider. Given the voltage across the load resistor and its resistance, the resistance of the sensor could be derived.
************************************************************************************/
float MQResistanceCalculation(int raw_adc, float rl_value)
{
  return  (long)((long)(1024 * 1000 * (long)rl_value) / raw_adc - (long)rl_value);
  ;
}

/***************************** MQCalibration (R0) ****************************************
  Input:   mq_pin - analog channel
  Output:  Ro of the sensor
  Remarks: This function assumes that the sensor is in clean air. It use
         MQResistanceCalculation to calculates the sensor resistance in clean air.        .
************************************************************************************/
float MQCalibration(int mq_pin, double ppm, double rl_value, float *pcurve )
{
  int i;
  float val = 0;

  for (i = 0; i < CALIBRATION_SAMPLE_TIMES; i++) {      //take multiple samples
    val += MQResistanceCalculation(analogRead(mq_pin), rl_value);
    delay(CALIBRATION_SAMPLE_INTERVAL);
  }
  val = val / CALIBRATION_SAMPLE_TIMES;                 //calculate the average value
  //Ro = Rs * sqrt(a/ppm, b) = Rs * exp( ln(a/ppm) / b )

  return  (long)val * exp((log(pcurve[0] / ppm) / pcurve[1]));

}

/*****************************  MQRead (Rs) *********************************************
  Input:   mq_pin - analog channel
  Output:  Rs of the sensor
  Remarks: This function use MQResistanceCalculation to caculate the sensor resistenc (Rs).
         The Rs changes as the sensor is in the different consentration of the target
         gas. The sample times and the time interval between samples could be configured
         by changing the definition of the macros.
************************************************************************************/
float MQRead(int mq_pin, float rl_value)
{
  int i;
  float rs = 0;

  for (i = 0; i < READ_SAMPLE_TIMES; i++) {
    rs += MQResistanceCalculation(analogRead(mq_pin), rl_value);
    delay(READ_SAMPLE_INTERVAL);
  }

  rs = rs / READ_SAMPLE_TIMES;

  return rs;
}

/*****************************  MQGetPercentage **********************************
  Input:   rs_ro_ratio - Rs divided by Ro
         pcurve      - pointer to the curve of the target gas
  Output:  ppm of the target gas
  Remarks: By using the slope and a point of the line. The x(logarithmic value of ppm)
         of the line could be derived if y(rs_ro_ratio) is provided. As it is a
         logarithmic coordinate, power of 10 is used to convert the result to non-logarithmic
         value.
************************************************************************************/
int  MQGetPercentage(float rs_ro_ratio, float ro, float *pcurve)
{
  return (double)(pcurve[0] * pow(((double)rs_ro_ratio), pcurve[1]));
}

The code to test the sensor, without integrating firebase and ESP8266, is as follows:

//Source: https://github.com/empierre/arduino-mysensors-contribs/blob/master/AirQuality-Multiple_Gas_Sensor1_4.ino

// Libraries
#include <SPI.h>
#include <Wire.h>
#include <DHT.h>
#include <Adafruit_BMP085.h>

//Hardware Macros
#define MQ138 (5) //Analog 5 input
#define RL_VALUE (10000) //Load resistance in ohms
//Software macros
#define         CALIBRATION_SAMPLE_TIMES     (40)    //define how many samples you are going to take in the calibration phase
#define         CALIBRATION_SAMPLE_INTERVAL  (500)   //define the time interal(in milisecond) between each samples in the
                                                     //cablibration phase
#define         READ_SAMPLE_INTERVAL         (50)    //define how many samples you are going to take in normal operation
#define         READ_SAMPLE_TIMES            (5)     //define the time interal(in milisecond) between each samples in

//Globals
float AcetoneCurve[2] = {3.720, -2.222}; //A, B
float R0 = 10000; //Initialized to 10k ohms
unsigned long SLEEP_TIME = 600; // Sleep time between reads (in seconds)
int val = 0;          // variable to store the value coming from the sensor
//idfk what this is
float calcVoltage = 0;
float dustDensity = 0;
boolean metric = true;

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

void loop() {
  // put your main code here, to run repeatedly:
  int raw = analogRead(MQ138);
  static float Ro = MQCalibration(MQ138, 25, RL_VALUE, AcetoneCurve);    //Assuming 25ppm of acetone in clean air?
  //https://www.health.ny.gov/environmental/indoors/air/contaminants/acetone.htm#:~:text=Levels%20of%20acetone%20are%20typically,common%20ingredient%20in%20many%20products.
  float Rs = MQRead(MQ138, RL_VALUE);
  float ratio = Rs / Ro;
  int ppm = MQGetPercentage(ratio, Ro, AcetoneCurve);
  Serial.println(raw);
  Serial.print("PPM: ");
  Serial.println(ppm);
}

//Functions
/****************** MQResistanceCalculation ****************************************
Input:   raw_adc - raw value read from adc, which represents the voltage
Output:  the calculated sensor resistance
Remarks: The sensor and the load resistor forms a voltage divider. Given the voltage across the load resistor and its resistance, the resistance of the sensor could be derived.
************************************************************************************/
float MQResistanceCalculation(int raw_adc,float rl_value)
{
  return  (long)((long)(1024*1000*(long)rl_value)/raw_adc-(long)rl_value);
;
}

/***************************** MQCalibration (R0) ****************************************
Input:   mq_pin - analog channel
Output:  Ro of the sensor
Remarks: This function assumes that the sensor is in clean air. It use
         MQResistanceCalculation to calculates the sensor resistance in clean air.        .
************************************************************************************/
float MQCalibration(int mq_pin, double ppm, double rl_value,float *pcurve )
{
  int i;
  float val=0;

  for (i=0;i<CALIBRATION_SAMPLE_TIMES;i++) {            //take multiple samples
    val += MQResistanceCalculation(analogRead(mq_pin),rl_value);
    delay(CALIBRATION_SAMPLE_INTERVAL);
  }
  val = val/CALIBRATION_SAMPLE_TIMES;                   //calculate the average value
  //Ro = Rs * sqrt(a/ppm, b) = Rs * exp( ln(a/ppm) / b )

  return  (long)val*exp((log(pcurve[0]/ppm)/pcurve[1]));

}

/*****************************  MQRead (Rs) *********************************************
Input:   mq_pin - analog channel
Output:  Rs of the sensor
Remarks: This function use MQResistanceCalculation to caculate the sensor resistenc (Rs).
         The Rs changes as the sensor is in the different consentration of the target
         gas. The sample times and the time interval between samples could be configured
         by changing the definition of the macros.
************************************************************************************/
float MQRead(int mq_pin,float rl_value)
{
  int i;
  float rs=0;

  for (i=0;i<READ_SAMPLE_TIMES;i++) {
    rs += MQResistanceCalculation(analogRead(mq_pin),rl_value);
    delay(READ_SAMPLE_INTERVAL);
  }

  rs = rs/READ_SAMPLE_TIMES;

  return rs;
}

/*****************************  MQGetPercentage **********************************
Input:   rs_ro_ratio - Rs divided by Ro
         pcurve      - pointer to the curve of the target gas
Output:  ppm of the target gas
Remarks: By using the slope and a point of the line. The x(logarithmic value of ppm)
         of the line could be derived if y(rs_ro_ratio) is provided. As it is a
         logarithmic coordinate, power of 10 is used to convert the result to non-logarithmic
         value.
************************************************************************************/
int  MQGetPercentage(float rs_ro_ratio, float ro, float *pcurve)
{
  return (double)(pcurve[0] * pow(((double)rs_ro_ratio), pcurve[1]));
}

Any help would be much appreciated!


text:
How to install FTDI Serial Drivers on Mac?
I'm following this tutorial on how to install FTDI drivers on macOS, but am facing some issues. After downloading the USB Serial Driver version 2.4.4 (for OS X 10.14) from FTDI Chip's virtual COM port (VCP) driver page (recommended by the tutorial), I still don't see any usbserial option listed under the Serial Port tab, shown below.

Because I'm running macOS Monterrey (12.0.1), I also tried downloading the Beta driver release (version 1.5.0) for OS X 10.15 and macOS 11/12. After running the installer from my Applications folder (as recommended), I get the following result, indicating success, but the options list remains the same as shown above.

Are there any workarounds? For reference, I am using Arduino IDE 2.0.0.

I have just managed to get the FTDI set up for my M1 mac using the Pro Mini. I think the issue is that newer macs automatically block the FTDI serial connection from being used as a com port. You need to install a program called D2XXHelper to prevent this behaviour.
I did the following, hopefully this will work for you too:

Install FTDI VCP Driver, found here: Scroll down to first table and find the latest Mac OS drivers. There are 2, the 2.4.4 version and the 1.5 version. I think you need to use the 1.5 version for the M1 but I’m not sure because I installed both before I did the next steps to get it working.
Install the D2XXHelper found here: Scroll down to first table and look in the comments column for the Mac OS row to find the download link.
After installing the D2XXHelper, you should get a security prompt saying system extension blocked. Follow this guide which shows how to provide permission for the system extension to be applied – this requires going into recovery mode and requires several computer restarts.
After following the steps in the guide, you should have enabled the D2XXHelper system extensions to be applied, in which case when you connect your Arduino to your computer via the FTDI connector, the Arduino IDE 2 should now recognise that a device has been connected via the FTDI virtual com port.
optional – to check that your FTDI is connected correctly to your Arduino, connect it up, Open a Terminal window and type “ls /dev/tty.*” and run this command. If the FTDI is connected properly then a usb serial device should show up in the results to this command.


text:
How to turn off the display of line numbers on Mac Arduino IDE?
I'm trying to turn off line numbers on the Mac Arduino IDE but don't see the option for it after navigating to Arduino IDE > Preferences. Below is a screenshot of what I am seeing.

I saw this question asked previously, but there is no File > Preferences path on Mac. I am using Version 2.0.0 on macOS (10.14 or newer).

OT, just out of curiosity: Why do you want them to be off? For example, I cannot work without line numbers.

I don't see a proper place to do this in the 2.0.0 IDE preferences. However, modifying the .arduinoIDE/setting.json file to include "editor.lineNumbers": "off", seems to work.
{
 "editor.lineNumbers": "off",
 "editor.fontSize": 14,
 ...
}

Edgar Bonet pointed out in a comment that there's still a bunch of empty space in that region. The image above doesn't do a good of showing why though. In the below screenshots I've told the IDE to set a breakout and hovered over where folding region so it displays the fold indicators to make somewhat easier to see that and compare what effect on width results from disabling these things.
If you want to save a bit more space you can add turn off the code folding feature, which removes the spaced that would be used for fold indicators with an additional "editor.folding": "false", in the settings.json file.
For comparison, here's everything enabled, numbers but no folding, folding but no numbers, no folding and no numbers:

I haven't yet found out how to turn off the display of break-point indicators. I assume that it is possible though.

Looks like it didn't remove from the layout the column dedicated to the line numbers: it's now just wasted space.

Yeah, it doesn't get rid of the entire area they inhabit. That space is also used for the indicators for code folding and indicators for breakpoints. So the space is only narrowed so much by the removal of the line numbers themselves. Maybe, I'll look into seeing if there's a way to remove the entire area or what it looks like if told not to indicate breakpoints or folding.


text:
How to program Attiny12 with Arduino?
I bought a bunch of Attiny12's from Digikey without checking if I can even program them with an Arduino. I've looked around a bunch, and I've only ever found ways to program Attiny13 and Attiny10.
Strangely, one of the board packages I downloaded had board information for the Attiny12 in the avrdude.conf file, but I can't select it in the Arduino IDE. I've tried to change the Attiny13 info in the config file to the Attin12 and just selecting the Attiny13, but I'm getting the following error:
         Using Port                    : COM3
         Using Programmer              : stk500v1
         Overriding Baud Rate          : 19200
         AVR Part                      : ATtiny13
         Chip Erase delay              : 20000 us
         PAGEL                         : P00
         BS2                           : P00
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom         4     8    64    0 no         64    0      0  9000 20000 0xff 0xff
           flash          4     5   128    0 no       1024    0      0  4500 20000 0xff 0xff
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00

         Programmer Type : STK500
         Description     : Atmel STK500 Version 1.x firmware
         Hardware Version: 2
         Firmware Version: 1.18
         Topcard         : Unknown
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.03s

avrdude: Device signature = 0x000000 (retrying)

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000 (retrying)

Error while burning bootloader.
Reading | ################################################## | 100% 0.03s

avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.

Anyway I can program the Attiny12 without resorting to a dedicated programmer?

are you asking about programming with Arduino or with Arduino IDE?

info about programming is almost non-existent ... maybe info here can be used to write a programming sketch ... http://web.archive.org/web/20090823113448/http://www.xs4all.nl:80/~sbolt/e-spider_prog.html

here is the datasheet for Attiny12 ... it's the 94 page one labeled ATtiny11/12 ... https://web.archive.org/web/20090417081256/http://www.atmel.com/dyn/products/alldatasheets.asp?family_id=607

LOL. Well, in some ways I love the question, but you're not going to run an Arduino sketch on this thing. And it's for the same reason. The ATTiny12 has no RAM. I don't mean little RAM, I mean literally no RAM and no way to add RAM to its internal address space. Basically, all you have inside the chip for mutable state is the general purpose registers and whatever peripheral registers you can cram stuff into. gcc/g++ do not support it as a C or C++ target. So, if you want to know about ardunoisp.ino to program an assembly program, okay. But, you're not going to code this chip with Arduino.

@timemage Huh, I completely missed that. So what's the purpose of this microcontroller?

Whatever purpose you can dream up with assembly code. It is theoretically possible to make C run on such a thing with extraordinary limitations that might technically violate even the non-hosted standard. But, gcc does not do this. The attiny13 is very similar but has some RAM and can be coded be coded via an Arduino core in a very limited way. If you want to stick with this tiny series, use the the ATTiny85, but really, still don't exactly recommend it. If you're new to all this stuff, you really should not go smaller the an Arduino UNO/Nano/Promini in terms of memories.

If "program Attiny12 with Arduino" was intended to mean, "use an Ardunio board to put code onto a Attiny12", then your question in still unanswered and on topic (so far as I'm concerned anyway) though may need clarification.  If it was intended to mean "use Arduino code/core/ecosystem on an Attiny12" then it's basically answered. You can delete the question or you can clarify in the question that that's what you meant and I'll convent the essence of the comment into an answer.

@timemage The former - I wanted to use an Arduino Uno as a programmer for Attiny, so I don't have to buy a dedicated programmer.


text:
Arduino cannot sync
I have seen many of these problems and followed all the instructions i can find, i made sure the com was the correct one, i made sure th e drivers were installed. I cannot upload my sketch...anyone else have any ideas, ive been working on this forever trying to figure it out...
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-objcopy" -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load
--no-change-warnings --change-section-lma .eeprom=0  "C:\Users\reneg\AppData\Local\Temp\arduino_build_1951/HelloWorld.ino.elf" "C:\Users\reneg\AppData\Local\Temp\arduino_build_1951/HelloWorld.ino.eep" "C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-objcopy" -O ihex -R .eeprom  "C:\Users\reneg\AppData\Local\Temp\arduino_build_1951/HelloWorld.ino.elf" "C:\Users\reneg\AppData\Local\Temp\arduino_build_1951/HelloWorld.ino.hex" Multiple libraries were found for "LiquidCrystal.h"  Used: C:\Users\reneg\Documents\Arduino\libraries\LiquidCrystal  Not used: C:\Program Files (x86)\Arduino\libraries\LiquidCrystal Using library LiquidCrystal at version 1.0.5 in folder: C:\Users\reneg\Documents\Arduino\libraries\LiquidCrystal  Sketch uses 1900 bytes (5%) of program storage space. Maximum is 32256 bytes. Global variables use 59 bytes (2%) of dynamic memory, leaving 1989 bytes for local variables. Maximum is 2048 bytes. C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega328p
-carduino -PCOM1 -b115200 -D -Uflash:w:C:\Users\reneg\AppData\Local\Temp\arduino_build_1951/HelloWorld.ino.hex:i

avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM1
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200 avrdude: stk500_recv(): programmer is not responding avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x24 avrdude: stk500_recv(): programmer is not responding avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x24 avrdude: stk500_recv(): programmer is not responding avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x24 avrdude: stk500_recv(): programmer is not responding avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x24 avrdude: stk500_recv(): programmer is not responding avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x24 avrdude: stk500_recv(): programmer is not responding avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x24 avrdude: stk500_recv(): programmer is not responding avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x24 avrdude: stk500_recv(): programmer is not responding avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x24 avrdude: stk500_recv(): programmer is not responding avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x24 avrdude: stk500_recv(): programmer is not responding avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x24

avrdude done.  Thank you.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

Ok figured it out.......had to change the board type/////


text:
Requires accurate RGB color values by the tcs3200 RGB color sensore
I used the TCS3200 sensor to read the RGB color values.First, I calibrated the sensor with white and black colors.The sensor detects red, blue, and green correctly, but does not give an accurate value.For example, green is 105 190 150 instead of 0 255 0 .  I have to recognize the brown copper with the RGB value 138 73 49 .But it seems that I can not recognize this color with this method.I will be grateful if you can guide me.
#define S0 4
#define S1 5
#define S2 6
#define S3 7
#define sensorOut 8
int redPW = 0 ;
int greenPW = 0 ;
int bluePW = 0 ;

void setup() {
  // Set S0 - S3 as outputs
  pinMode(S0, OUTPUT);
  pinMode(S1, OUTPUT);
  pinMode(S2, OUTPUT);
  pinMode(S3, OUTPUT);
  pinMode(sensorOut, INPUT);

  // Setting frequency-scaling to 20%
  digitalWrite(S0,HIGH);
  digitalWrite(S1,LOW);

  Serial.begin(9600);

}

void loop() {

// Calibration Values
int redMin=40;// Red minimum value
int redMax=470;//346 Red maximum value
int greenMin=40;// Green minimum value
int greenMax=510;//348 Green maximum value
int blueMin=30;// Blue minimum value
int blueMax=390;//262 Blue maximum value

int redValue;
int greenValue;
int blueValue;

//Read Red Pulse Width
digitalWrite(S2,LOW);
digitalWrite(S3,LOW);
// Read the output Pulse Width
redPW = pulseIn(sensorOut,LOW);
redValue=map(redPW, redMin,redMax,255,0);
delay(200);

// Read Green Pulse Width
digitalWrite(S2,HIGH);
digitalWrite(S3,HIGH);
// Read the output Pulse Width
greenPW = pulseIn(sensorOut,LOW);
greenValue=map(greenPW, greenMin,greenMax,255,0);
delay(200);

// Read Blue Pulse Width
digitalWrite(S2,LOW);
digitalWrite(S3,HIGH);
// Read the output Pulse Width
bluePW = pulseIn(sensorOut,LOW);
blueValue=map(bluePW, blueMin,blueMax,255,0);
delay(200);

// Print output to Serial Monitor
Serial.print("redValue = ");
Serial.print(redValue);
Serial.print(" - greenValue = ");
Serial.print(greenValue);
Serial.print(" - blueValue = ");
Serial.println(blueValue);

}

I'm not sure I really get your question, but it kind of sounds like what you want is to convert RGB to HSV and compare the hue against your target's hue, mostly irrespective of value and maybe to some degree saturation as well.

How do you perform the calibration? The spectrum of the light source is essential for the calibration! Is it a green LED?

Btw, did you take a look at the spectral sensitivity of the sensor on page 5? Your reading sound reasonable for a green LED...

How exactly are you calibrating a color sensor with only white and black?

As I said, you MUST either

know the spectrum of the light source that exposes your sample or
calibrate the sensor under the exact same light you use for detection later on.

However, the actual calibration values don't matter at all. It should be as simple as saving the value you get for copper as a reference and compare your test color with that value, including some margin, of course. Any sensor will always have specific/individual properties, like the spectral sensitivity in case of the TCS3200. But the reason of calibration is that you don't have to bother.


text:
I am trying to use Arduino Uno as a hid device to login Windows but I cannot use Modifier keys to Lock Windows
uint8_t buf[8] = { 0 };
#include <SPI.h>
#include <MFRC522.h> // RFID library
#define SS_PIN 10 //RX slave select
#define RST_PIN 9
int gled = 7; // optional
int rled = 4;// optional
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance.
String card_ID=""; //
String password="" ; // Change It To Your Windows / fb / any Account's Password
String rfid="8";// UID (unique Id Code Of Your Rfid Tag)
void setup() {
  Serial.begin(9600); // Initialize serial communications with the PC
  SPI.begin();  // Init SPI bus
  mfrc522.PCD_Init(); // Init MFRC522 card
  pinMode(gled,OUTPUT);
  pinMode(rled,OUTPUT);
}
void loop() {
  //look for new card
   if ( ! mfrc522.PICC_IsNewCardPresent()) {
  return;
 }
 if ( ! mfrc522.PICC_ReadCardSerial()) {
  return;//if read card serial(0) returns 1, the uid struct contians the ID of the read card.
 }
 for (byte i = 0; i < mfrc522.uid.size; i++) {
   card_ID += mfrc522.uid.uidByte[i];
 }
// Serial.println(card_ID);
       if(card_ID==rfid){digitalWrite(gled,HIGH);
      typeLiteralString(password);
      pressKey("enter"); releaseKey("enter");
     digitalWrite(gled,LOW); delay(200);digitalWrite(gled,HIGH); delay(200);digitalWrite(gled,LOW);
      }
      if(card_ID!=password){
digitalWrite(rled,HIGH);    digitalWrite(rled,LOW); delay(200);digitalWrite(rled,HIGH); delay(200);digitalWrite(rled,LOW);  }      else{ goto cont;}
delay(1000);
cont:
delay(1000);
card_ID="";
}
boolean isModifier(int keycode) {
    boolean result = false;
    if (keycode >= 224 && keycode <= 231) { // if the keycode is a modifier key
        result = true;
    }
    return result;
}

void pressModifier(String keyname) {
    pressModifier(getKeycode(keyname));
}
void pressModifier(int keycode) {
    int modifiermask = 0;
    if (isModifier(keycode)) { // if the keycode represents a modifier key
        modifiermask = getModifierMask(keycode);
        buf[0] = buf[0] | modifiermask;
        Serial.write(buf, 8); // Send key report
    }
}

void releaseModifier(String keyname) {
    releaseModifier(getKeycode(keyname));
}
void releaseModifier(int keycode) {
    int modifiermask = 0;
    if (isModifier(keycode)) { // if the keycode represents a modifier key
        modifiermask = getModifierMask(keycode);
        buf[0] = buf[0] & (~modifiermask);
        Serial.write(buf, 8); // Send key report
    }
}
void releaseAllModifiers() {
    buf[0] = B00000000;
    Serial.write(buf, 8); // Send key report
}

void pressKey(String keyname) {
    pressKey(getKeycode(keyname));
}
void pressKey(int keycode) { // TODO: cycle the 6 key spots in the report buffer instead of just using buf[2] each time.
    buf[2] = keycode;
    Serial.write(buf, 8); // Send key report
}

void releaseKey(String keyname) {
    releaseKey(getKeycode(keyname));
}
void releaseKey(int keycode) {
    // find the keycode in the report buffer, then set it to zero.
    int i=0;
    for (i=2; i<8; i++) {
        if (buf[i] == keycode) {
            buf[i] = 0;
        }
    }
    Serial.write(buf, 8); // Send key report
}
void releaseAllKeys() {
    int i=0;
    for (i=2; i<8; i++) {
        buf[i] = 0;
    }
    Serial.write(buf, 8); // Send key report
}

void pressSequenceOfKeys(const char * keySequence[], int numberOfKeys) {
    // This function can be good for pressing a few keys while holding a modifier down for example.

    int i = 0;
    for (i=0; i<numberOfKeys; i++) {
        pressKey(keySequence[i]);
        releaseKey(keySequence[i]);
    }
}

void typeLiteralString(String string) {
    char charArray[string.length()+1];
    string.toCharArray(charArray, string.length()+1);
    typeLiteralString(charArray, string.length());
}
void typeLiteralString(char string[], int stringLength) { // stringLength is the length of the printable string without considering the null byte.
    // This function will type the given string exactly as given, automatically pressing left_shift where necessary for capitals and symbols.

    // just in case:
    releaseAllKeys();
    releaseAllModifiers();

    boolean charNeedsShift = false;
    boolean shiftIsPressed = false;

    int i=0;
    for (i=0; i<stringLength; i++) {
        charNeedsShift = characterNeedsShift(string[i]);
        if (charNeedsShift && !shiftIsPressed) {
            pressModifier("left_shift");
            shiftIsPressed = true;
        }
        else if (!charNeedsShift && shiftIsPressed) {
            releaseModifier("left_shift");
            shiftIsPressed = false;
        }
        pressKey(String(string[i])); // without converting the char in string[i] to a String, arduino would prefer the pressKey(int) function instead of the pressKey(String) function, casting the char to a keycode (int) instead of a keyname (String).
        releaseKey(String(string[i])); // same as previous comment, but with releaseKey().
    }

    releaseAllModifiers();
}

boolean characterNeedsShift(char character) {
    int needsModifier = false;
    if ( // look up an ascii table and this will make sense.
        (character >= 33 && character <= 38)
        || (character >= 40 && character <= 43)
        || (character == 58)
        || (character == 60)
        || (character >= 62 && character <= 90)
        || (character >= 94 && character <= 95)
        || (character >= 123 && character <= 126)
    ) {
        needsModifier = true;
    }
    return needsModifier;
}

int getKeycode(String keyname) {
    String key = String(keyname); // Use a copy so that we don't mutate the user's String. Not sure if this is needed, but just in case. TODO: find out.
    key.toLowerCase();

    int keycode = 0; // keycode of zero means nothing pressed.

    // non-modifier keys
    if      (key == "a") { keycode =  4; }
    else if (key == "b") { keycode =  5; }
    else if (key == "c") { keycode =  6; }
    else if (key == "d") { keycode =  7; }
    else if (key == "e") { keycode =  8; }
    else if (key == "f") { keycode =  9; }
    else if (key == "g") { keycode = 10; }
    else if (key == "h") { keycode = 11; }
    else if (key == "i") { keycode = 12; }
    else if (key == "j") { keycode = 13; }
    else if (key == "k") { keycode = 14; }
    else if (key == "l") { keycode = 15; }
    else if (key == "m") { keycode = 16; }
    else if (key == "n") { keycode = 17; }
    else if (key == "o") { keycode = 18; }
    else if (key == "p") { keycode = 19; }
    else if (key == "q") { keycode = 20; }
    else if (key == "r") { keycode = 21; }
    else if (key == "s") { keycode = 22; }
    else if (key == "t") { keycode = 23; }
    else if (key == "u") { keycode = 24; }
    else if (key == "v") { keycode = 25; }
    else if (key == "w") { keycode = 26; }
    else if (key == "x") { keycode = 27; }
    else if (key == "y") { keycode = 28; }
    else if (key == "z") { keycode = 29; }

    else if (key == "1" || key == "!") { keycode = 30; }
    else if (key == "2" || key == "@") { keycode = 31; }
    else if (key == "3" || key == "#") { keycode = 32; }
    else if (key == "4" || key == "$") { keycode = 33; }
    else if (key == "5" || key == "%") { keycode = 34; }
    else if (key == "6" || key == "^") { keycode = 35; }
    else if (key == "7" || key == "&") { keycode = 36; }
    else if (key == "8" || key == "*") { keycode = 37; }
    else if (key == "9" || key == "(") { keycode = 38; }
    else if (key == "0" || key == ")") { keycode = 39; }

    else if (key == "enter" || key == "return")     { keycode = 40; }
    else if (key == "escape" || key == "")    { keycode = 41; }
    else if (key == "backspace" || key == "") { keycode = 42; }
    else if (key == "tab" || key == "  ")      { keycode = 43; }
    else if (key == "space" || key == " ")      { keycode = 44; }

    else if (key == "-" || key == "_")  { keycode = 45; }
    else if (key == "=" || key == "+")  { keycode = 46; }
    else if (key == "[" || key == "{")  { keycode = 47; }
    else if (key == "]" || key == "}")  { keycode = 48; }
    else if (key == "\\" || key == "|") { keycode = 49; }
    else if (key == ";" || key == ":")  { keycode = 51; }
    else if (key == "'" || key == "\"") { keycode = 52; }
    else if (key == "`" || key == "~")  { keycode = 53; }
    else if (key == "," || key == "<")  { keycode = 54; }
    else if (key == "." || key == ">")  { keycode = 55; }
    else if (key == "/" || key == "?")  { keycode = 56; }

    // TODO: Fix these keycodes. V
    else if (key == "capslock")         { keycode = 58; }

    else if (key == "f1")      { keycode = 59; }
    else if (key == "f2")      { keycode = 60; }
    else if (key == "f3")      { keycode = 61; }
    else if (key == "f4")      { keycode = 62; }
    else if (key == "f5")      { keycode = 63; }
    else if (key == "f6")      { keycode = 64; }
    else if (key == "f7")      { keycode = 65; }
    else if (key == "f8")      { keycode = 66; }
    else if (key == "f9")      { keycode = 67; }
    else if (key == "f10")     { keycode = 68; }
    else if (key == "f11")     { keycode = 69; }
    else if (key == "f12")     { keycode = 70; }

    else if (key == "print_screen")    { keycode = 70; }
    else if (key == "scroll_lock")     { keycode = 71; }
    else if (key == "pause")           { keycode = 72; }
    else if (key == "insert")          { keycode = 73; }
    else if (key == "home")            { keycode = 74; }
    else if (key == "page_up")         { keycode = 75; }
    else if (key == "delete")          { keycode = 76; }
    else if (key == "end")             { keycode = 77; }
    else if (key == "page_down")       { keycode = 78; }

    else if (key == "right_arrow")     { keycode = 79; }
    else if (key == "left_arrow")      { keycode = 80; }
    else if (key == "down_arrow")      { keycode = 81; }
    else if (key == "up_arrow")        { keycode = 82; }

    else if (key == "numlock" || key == "clear")   { keycode = 83; }

    //TODO: keypad and miscellaneous keys if you want them.

    // modifier keys.
    else if (key == "left_control")  { keycode = 224; }
    else if (key == "left_shift")    { keycode = 225; }
    else if (key == "left_alt")      { keycode = 226; }
    else if (key == "left_gui")      { keycode = 227; }

    else if (key == "right_control") { keycode = 228; }
    else if (key == "right_shift")   { keycode = 229; }
    else if (key == "right_alt")     { keycode = 230; }
    else if (key == "right_gui")     { keycode = 231; }

    return keycode;
}

int getModifierMask(String keyname) {
    return getModifierMask(getKeycode(keyname));
}
int getModifierMask(int keycode) { // return value of 0 means key is not a modifier.
    int modifiermask = 0;

    // NOTE: these are not the usage keycodes like for other keys, but rather the bit masks.
    if      (keycode == 224) { modifiermask = B00000001; } // left ctrl
    else if (keycode == 225) { modifiermask = B00000010; } // left shift
    else if (keycode == 226) { modifiermask = B00000100; } // left alt
    else if (keycode == 227) { modifiermask = B00001000; } // left gui
    else if (keycode == 228) { modifiermask = B00010000; } // right ctrl
    else if (keycode == 229) { modifiermask = B00100000; } // right shift
    else if (keycode == 230) { modifiermask = B01000000; } // right alt
    else if (keycode == 231) { modifiermask = B10000000; } // right gui

    return modifiermask;
}

The Uno cannot be used as HID. It has no native USB support. Your code relies on some program running on the PC

Or have you reflashed your USB chip with some HID firmware?

what are you using on windows side to press keys?

are you able to type text into a notepad window?


text:
My Arduino smokes every time I connect an AC/DC wall adapter to it. Can someone help me to fix it?
I copied the schematic below and when I ran the code from my laptop, it worked well but every time I unplug it to my laptop and connect an ac dc wall adapter, my Arduino smokes. Why does it smoke and how to fix it so that I can connect an AC/DC wall adapter to power my Arduino? EDIT from the comments: My AC/DC adapter has 19.5V DC out.

disconnect the motor ... the arduino voltage regulator does not have enough capacity to run it  .... disconnect the motor red wire from the arduino ... disconnect the top black wire on the relay from the arduino .... insert a battery between the motor red wire and the top relay black wire

is there any way to power this up without the use of my laptop?

@VE7JRO the output voltage is 19.5 V and i am connecting it through the barrel jack

@jsotola can i still use or connect a wall adapter if I already connected it to a battery or no need?

the relay contacts is simply a switch ... use it to turn on the battery power to the motor ... do not connect any part of the motor circuit to the arduino .... the arduino and the wall adapter are electrically separate from the motor and the battery

@jsotola so i can still use the wall adapter to power my sensor?

@jsotola okay thank you very much for the help! appreciate it :)))

19.5V on the barrel connector is too high, especially when powering a motor. It needs maybe half that. The "smoking" part is probably the voltage regulator on your Arduino.

Just as a fun fact. It's called a "Magic Smoke" https://en.wikipedia.org/wiki/Magic_smoke

@StarCat Instead of a 19.5 V on the barrel connector can I use 12 V?

@FilipFranik Thank you for the information, I could really use it!

How will I know how much power supply do i need to make this work

You'll have to know how much current your motor draws. Ideally, you power the motor from a different supply than directly from the Arduino board because the voltage regulator on the Arduino can only deliver a limited amout of current. If you do decide to power the motor from the board, make sure the voltage of the external power supply is not too high (i.e. it needs to be just a few volts above the regulated output of 5V), I would aim for 7-9V at 1 A.

@StarCat so if a use a wall adapter from 7-9 V, it would be enough to power this up?

That should work but you should make sure it can deliver enough current and it would be better to power the motor from a separate supply (or at least not via the Arduino voltage regulator).

@StarCat thank you so much for answering! It helped me a lot!!!!!

As already stated in the comments, the voltage of your power supply is the problem. The Arduino has a linear voltage regulator at the Vin pin. It dissipates the excess voltage as heat. The higher the supplied voltage, the lower the current, that you can draw before it overheats. The regulator on a genuine Arduino should go into thermal shutdown, while the regulators on most cheap clones will just get destroyed.
19.5V is too high for the Arduino. The Vin pin is meant for  6 to 12V max. You need a power supply, that can provide a voltage in that range. Or you can buy a regulated power supply, that directly gives you the 5V, that the Arduino needs.
Also you should be really carefull with powering the motor through the Arduinos 5V pin. Motors can easily draw a big amount of current. When drawing too much current through the Arduino (to be specific: through the voltage regulator or the protection diode), the same as explained above will happen. Only very small motors can be supplied through the Arduino. As you use a relay to control it, I guess the motor draws a lot of current. You need tp connect it directly to a fitting power supply, so that the current for it does not flow through the Arduino.
And always be sure, that the used parts can work with the voltage, that you want to supply, including the motor.

Sorry but can i use a wall adapter without an output of 12 V and still power up the motor and sensor?

What do you mean by without 12V? With what voltage instead. If you only have a supply with more voltage, you need to buy an extra voltage regulator to bring the voltage down. Be sure, that is is a switching regulator instead of a linear one, and that i can provide more that the needed current

I'm sorry I meant with 12V, thank you but is it possible to power all this up with that output? Also how will I know how much output volts does my arduino needs to power this up? Sorry, I'm new to this and i really appreciate your answer

also i would also like to know how will i know the right voltage or power supply to make this work

You need to check, with which voltage your motor can work. Your supplier should have this information. Or - if you have one - look the the motors datasheet. The Arduino needs either 5V on USB/5V pin or 6V - 12V on the Vin pin. Get a power supply, that fulfills the requirements of the Arduino and the motor, and that can provide enough current for both your Arduino and the motor (plus a bit overhead). Then it should work

so if I use a wall adapter between 6V to 12V and instead of connecting the motor to the 5V in the arduino, I connect it to the vin pin? would it work?

Yes, the 6V to 12V supply to Vin and the motor. Of course only if the motor can work with that voltage

Oh okay sir!!!! thank you so much for helping and teaching me, I've learned a lot!