BAD USB Atmega32u4 - Problem with performing various activities on one USB - if-statement

I have a problem with the Atmega32u4 board. I'm creating a program on BadUSB, which, according to assumptions, should do 3 different things. The problem is that in between these activities the computer shuts down. My idea was a simple counter with if statements, but the board doesn't save the current state permanently. I was thinking about detecting the situation he is currently in, but I have no idea how to do it. Could you please help me?
Functionality 1 - locked computer, opening CMD, entering the command.
Turning off the computer
Functionality 2 - unlocked computer, opening CMD, entering the command.
Logging out of the account/unplugging the USB.
Functionality 3 - locked computer, opening CMD, entering the command.
Do you have any ideas how to detect these situations? Or possibly how to save the counter state "permanently"
I made something like this:
int i = 0;
if (i == 0){
//Opening CMD
Keyboard.press(KEY_LEFT_GUI);
Keyboard.press('r');
Keyboard.releaseAll();
delay(1000);
Keyboard.print("cmd.exe");
Keyboard.press(KEY_RETURN);
Keyboard.releaseAll();
delay(1000);
//First functionality
Keyboard.print("echo Task 1");
Keyboard.press(KEY_RETURN);
Keyboard.releaseAll();
delay(1000);
i++;
return;
}
else if (i == 1){
//Opening CMD
Keyboard.press(KEY_LEFT_GUI);
Keyboard.press('r');
Keyboard.releaseAll();
delay(1000);
Keyboard.print("cmd.exe");
Keyboard.press(KEY_RETURN);
Keyboard.releaseAll();
delay(1000);
//Second functionality
Keyboard.print("echo Task 2");
Keyboard.press(KEY_RETURN);
Keyboard.releaseAll();
delay(1000);
i++;
return;
}

The ATmega32U4 has a 1 kB builtin EEPROM (See Datasheeet here). You can use that to store a persistent state when the chip is turned off. You tagged your question as Arduino, so here is a guide to using EEPROM with Arduino Libraries.

Related

How to communicate with ATTiny85/Digispark via USB on PC?

Recently I'm trying to make a simple LED controller with ATTiny85/Digispark.
I tried to use DigiCDC lib to perform data IO
but it does not work on my PC (win10 x64).
test code:
#include <DigiCDC.h>
void setup()
{
pinMode(0, OUTPUT);
pinMode(1, OUTPUT);
SerialUSB.begin();
SerialUSB.println("hello world");
}
void loop()
{
digitalWrite(0, HIGH);
digitalWrite(1, HIGH);
delay(200);
digitalWrite(0, LOW);
digitalWrite(1, LOW);
delay(800);
SerialUSB.println("ping");
int ava = SerialUSB.available();
int buffer[ava];
// read buffer
for(int step = 0; step < ava; step++)
buffer[step] = SerialUSB.read();
// write buffer back
for(int step = 0; step < ava; step++)
SerialUSB.print(buffer[step]);
SerialUSB.println("==line end==");
delete buffer;
}
Official demo mentioned here (Arduino IDE - Files - Examples - DigiCDC - Echo) also did not work.
Once program is compiled and uploaded onto board, Windows shows a "Unknown USB device" notification. And no usable serial port devices can be found.
Are there missing some drivers?
Or DigiCDC lib is simply not working on Win10?
Or I should use another lib to achieve communication between PC and ATTiny85/Digispark via USB?
I would first check if the Blink sketch works to rule out driver issues. The ATTINY85 I have uses PIN '1' for the onboard LED. For reference, I got my devices here:
https://www.amazon.com/gp/product/B0836WXQQR/ref=ppx_yo_dt_b_search_asin_title?ie=UTF8&th=1
Also, make sure you don't plug the ATTINY into the USB port until the Arduino IDE asks for it. So, just click the 'Upload' button and wait for it to compile and ask for the board. I'm assuming you know how to set up the IDE to work with the ATTINY. If not, this tutorial goes over that part:
https://www.instructables.com/Attiny85-USB-Development-Board-LED-Blinking-With-A/

To control LED using serial monitor arduino

My project is to control the LED by send '1' or '0' via serial monitor.
My task for this project is when '1' is send via serial monitor, the Led ON PIN 3 need to turn on and off every 2000ms. Then, when '0' is send via serial monitor, the LED need to be turn off until next '1' is send , so that the Led ON PIN 3 can be turn on and off every for 2000ms again. But it doesn't work for my code, can anyone tell me what is wrong in my code. Below is my code:
char data = 0; //Variable for storing received data
void setup()
{
Serial.begin(115200); //Sets the baud for serial data transmission
pinMode(3, OUTPUT); //Sets digital pin 3 as output pin
}
void loop()
{
if(Serial.available()>0 ) // Send data only when you receive data:
{
data = Serial.read(); //Read the incoming data send via serial monitor & store into data
Serial.print(data); //Print Value inside data in Serial monitor
Serial.print("\n");
while(data == '1') //Do looping so that when '1' send via serial monitor, the LED can blink
{
digitalWrite(3, HIGH);
delay(2000);
digitalWrite(3, LOW);
delay(2000);
}
while(data == '0') // Checks whether value of data is equal to 0
digitalWrite(3, LOW); //If value is 0 then LED turns OFF
}
}
You have several obvious mistakes... The main one being that you have locked execution into the while loops. So the execution path gets to "while data==" and it will stay there while the data equals that value. That value though can't change as you only read the value of data at the beginning of the function loop(). The only way this could work is if loop were serviced by a timer function and shared between two threads.
Replace your whiles with ifs, and run it using a while (1){loop();}; you may find it goes then. TBH, I'd add the Delay 2000 at the while loop level and only query the serial port every 2000mS too. It's bad karma to hammer things in a flywheel loop.
Change the structure of your loop.
Let the loop execute every 2000 ms. If there is data availabe to read from serial, read and parse it to update the 1 / 0 state.
Dependent on state, either let the state of the LED toggle between on and off or leave it in off state.

Why Serial Communications from Arduino stops after some time

I'm building a growbox/terrarium with arduino uno as the temperature controller. Simple sketch for arduino: if DS18B20 sensor giv less than 25'C than turn on relay, which the heating cable is connected to. Loop 30s, every time Serial.print(temperature) to the PC, where I'm collecting data and make timelapse photos. ---> Here is the problem.
After some time (from 15 min up to 4 hours). Serial communication with PC stops. When I'm trying to upload a new sketch to arduino I got an error msg:
avrdude: ser_open(): can't set com-state for "\.\COM3"
I need to unplug and plug in again USB cable (or turn it off and on in Windows Device Manager), also restart Python app that is collecting data. (Very unsatisfactory fix).
So my questions are:
1. Why?
2. How to fix it?
3. Or how to make some workaround, for example reset COM port from code (desirably python2.7)
PS. Example of what I'm doing and how it works(and do not works) here: Life of pepper
PS2. My goal is to make controllable habitate for plants, where I can see behaviours differs depending on the temp, day-duration, light-intensity, humidity.
Please help me :-) .
ARDUINO UNO SKETCH
#include <OneWire.h>
#include <DallasTemperature.h>
// Data wire is plugged into port 2 on the A
rduino
#define ONE_WIRE_BUS 2
#define PIN_HEATING 6
float temperatura = 30.0;
// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);
// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);
void setup(void)
{
// start serial port
Serial.begin(9600);
// Start up the library
sensors.begin();
pinMode(PIN_HEATING, OUTPUT);
}
void loop(void)
{
delay(30000);
if(temperatura<25.0){
digitalWrite(PIN_HEATING, HIGH);
}
else{
digitalWrite(PIN_HEATING, LOW);
}
sensors.requestTemperatures(); // Send the command to get temperatures
// After we got the temperatures, we can print them here.
// We use the function ByIndex, and as an example get the temperature from the first sensor only.
temperatura = sensors.getTempCByIndex(0);
Serial.print("#");
Serial.print(temperatura);
}
PYTHON2.7 RECEIVING PART
import serial #pySerial
ser = serial.Serial()
ser.port = "COM3"
ser.open()
data = ser.read_all().split("#")
datasize = len(data)
if datasize>1:
temp = data[datasize-1]
tempstr = " / " + str(temp) + "'C"
else:
tempstr=" / ----- "
I've experienced a similar problem in the past where the serial port would become unresponsive. The solution in my case wasn't very intuitive but worked nonetheless. Here's what might help you too:
Make sure the USB port you're using to connect the arduino isn't shared with other devices (for example using a USB multipoint hub). If you're using a desktop with multiple USB ports (usually found at the back of the desktop case), unplug all other USB devices (keyboard, mouse etc) and reconnect them to a different USB. Use the fastest USB port available available on your computer (USB 3.0 if present) and have it dedicated for communication with the arduino. The reason the communication port goes unresponsive sometimes is because of the momentary fluctuations in the voltage and/or current if you have several devices connected to it.
Make sure you have a stable power supply for you computer, voltage drifts due to heavy loading can sometimes cause PC peripherals to disconnect/reconnect.
If this doesn't work, try this quick software fix. Just before the delay(30000) statement in your code, add the following:
if(!Serial) { //check if Serial is available... if not,
Serial.end(); // close serial port
delay(100); //wait 100 millis
Serial.begin(9600); // reenable serial again
}
This might at least ensure continued operation operation of your application with out requiring your intervention.
So in my case the problem was solved by connecting my computer through proper surge supressor, formerly i had connectected it to wall with a simple cable, and I have old 2 wire, non-grounded, electric installation in my flat.

How do I read the output of an AT command in Arduino?

How do I capture the output from an AT command on an Arduino?
I'm using the Arduino Uno R3 with a GSM shield. I have all the AT commands (they can be seen here ) and I can enter them just fine if I use the terminal and get output. However how can I capture the resulting output via code? The code below shows what I've tried but it does not work. In particular where I attempt to get the analog input and then print out the result.
#include <SoftwareSerial.h>
SoftwareSerial mySerial(7, 8);
void setup()
{
char sensorValue[32] ="";
Serial.begin(9600);
mySerial.begin(9600);
Serial.println("\r");
//Wait for a second while the modem sends an "OK"
delay(1000);
//Because we want to send the SMS in text mode
Serial.println("AT+CMGF=1\r");
delay(1000);
mySerial.println("AT+CADC?"); //Query the analog input for data
Serial.println(Serial.available());
Serial.println(Serial.read()); //Print out result???
//Start accepting the text for the message
//to be sent to the number specified.
//Replace this number with the target mobile number.
Serial.println("AT+CMGS=\"+MSISDN\"\r");
delay(1000);
Serial.println("!"); //The text for the message
delay(1000);
Serial.write(26); //Equivalent to sending Ctrl+Z
}
void loop()
{
/*
if (mySerial.available())
Serial.write(mySerial.read());
if (Serial.available())
mySerial.write(Serial.read());
*/
}
I get the outputs:
AT+CMGF=1
AT+CADC? 21 13
or
AT+CMGF=1
AT+CADC? 18 65
Regardless of changes in my analog source
Take a look at the documentation of the SoftwareSerial read function here.
When you read from the GSM device serial interface, you cannot take for granted that there are bytes to be read on the buffer.
It's very likely that mySerial.read() returns -1 (no bytes available), as Arduino runs that code before the GSM device can provide something on the serial port.
You should use the available function (documentation here) to test the serial interface for incoming bytes. You could use it with a timeout to avoid infinite waiting.
The best thing you could try is to write a separate class to handle serial operations (read, write, timeouts, delays, etc).
Also, I wrote a GPRS driver for Arduino once.
I had a problem with the power supply that required me to install an extra capacitor on the GPRS device and use a power supply with more than 2A of output current.

Cannot connect Wifly to Arduino

I am just an Arduino beginner. I bought an Arduino Uno and a Wifly shield yesterday and I am not able to run the Wifly_Test example program come with WiFlySerial library.
When I look at Serial Monitor, I only saw 2 lines are printed out
1.Starting WiFly Tester.
2.Free memory:XXXX
How can I know that the Wifly Sheild that I bought is not faulty?
I soldered the heard ping to Wifly Shield and stacked it to Aurduino Uno and I can see the LEDs blinking on the Wifly Shield.
Do I need to reset the Wifly Sheild? How do I reset it?
Please point me to the most simple example on how to connect to the router.
I have also bought the shield and had trouble to start with.
If you have soldered the pins to the shield that should be fine but make sure you check they all have a connection and that they don't have solder running down the legs of the pins as this causes the shield to be temperamental.
Run the code below which is from the WiFly library (alpha 2 version) that can be found here:
http://forum.sparkfun.com/viewtopic.php?f=32&t=25216&start=30
Once you see that the shield has connected it will ask for an input, type $$$ and press enter... you have now entered the command line and CMD will be displayed.
If you do not know your network settings type scan and this will display them.
Then set your authentication by typing set wlan auth 3 (Mixed WPA1 & WPA2-PSK) or set wlan auth 4 (WPA2-PSK) this depends on the type of authentication you ise so pick the write one for your network.
Then type set wlan phrase YourPharsePhrase (Change YourPharsePhrase to whatever your WPA key is)
Then type join YourSSIDName (Change YourSSIDName to whatever your network name is)
You see something like this:
join YourSSIDName
Auto-Assoc YourSSIDName chan=1 mode=MIXED SCAN OK
Joining YourSSIDName now..
<2.15> Associated!
DHCP: Start
DHCP in 1234ms, lease=86400s
IF=UP
DHCP=ON
IP=10.0.0.116:2000
NM=255.255.255.0
GW=10.0.0.1
Listen on 2000
you are now connected to your network.
Hopefully this will get you up and running.
N.B. REMEMBER TO CAREFULLY CHECK YOUR PINS! I had great trouble with mine because only a small amount of solder is needed but enough to get a good connection, the balance of this was minute but enough that it wouldn't work. I used a magnifying to check mine in the end.
#include "WiFly.h" // We use this for the preinstantiated SpiSerial object.
void setup() {
Serial.begin(9600);
Serial.println("SPI UART on WiFly Shield terminal tool");
Serial.println("--------------------------------------");
Serial.println();
Serial.println("This is a tool to help you troubleshoot problems with the WiFly shield.");
Serial.println("For consistent results unplug & replug power to your Arduino and WiFly shield.");
Serial.println("(Ensure the serial monitor is not open when you remove power.)");
Serial.println();
Serial.println("Attempting to connect to SPI UART...");
SpiSerial.begin();
Serial.println("Connected to SPI UART.");
Serial.println();
Serial.println(" * Use $$$ (with no line ending) to enter WiFly command mode. (\"CMD\")");
Serial.println(" * Then send each command followed by a carriage return.");
Serial.println();
Serial.println("Waiting for input.");
Serial.println();
}
void loop() {
// Terminal routine
// Always display a response uninterrupted by typing
// but note that this makes the terminal unresponsive
// while a response is being received.
while(SpiSerial.available() > 0) {
Serial.write(SpiSerial.read());
}
if(Serial.available()) { // Outgoing data
//SpiSerial.print(Serial.read(), BYTE);
SpiSerial.write(Serial.read());
}
}
Sorry I forgot to mention , you reset the shield by going to the WiFly library and going to: WiFly/tools/HardwareFactoryReset
Then open the serial monitor and type in any character and this will start the reset.
Thanks everyone who tried to answer me. I finally solved my problem by using Arduino 0023 instead of 1.0.