1 Star 0 Fork 0

Aleej / Serial-code

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
SerialColor.ino 2.97 KB
一键复制 编辑 原始数据 按行查看 历史
Aleej 提交于 2022-04-07 01:15 . 提升稳定性,修改串口多发处理
/*Author: Aleej
Version: 1.0
Date: 2022/3/28
*/
#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
#include <avr/power.h> // Required for 16 MHz Adafruit Trinket
#endif
#define LED_PIN 2
// How many NeoPixels are attached to the Arduino?
#define LED_COUNT 20
// Declare our NeoPixel strip object:
Adafruit_NeoPixel strip(LED_COUNT, LED_PIN, NEO_RGB + NEO_KHZ800);
void setup() {
#if defined(__AVR_ATtiny85__) && (F_CPU == 16000000)
clock_prescale_set(clock_div_1);
#endif
// END of Trinket-specific code.
Serial.begin(9600);
strip.begin(); // INITIALIZE NeoPixel strip object (REQUIRED)
strip.show(); // Turn OFF all pixels ASAP
strip.setBrightness(250); // Set BRIGHTNESS to about 1/5 (max = 255)
// 初始化引脚
pinMode(3,OUTPUT);
pinMode(5,OUTPUT);
pinMode(6,OUTPUT);
// pinMode(9,OUTPUT);
analogWrite(3,0);
analogWrite(5,0);
analogWrite(6,0);
// analogWrite(9,0);
}
void loop() {
// Flowing rainbow cycle along the whole strip
recData();
delay(100);
}
char recData(){
int byteNum;
char buffData[128];
uint8_t r=0;
uint8_t g=0;
uint8_t b=0;
//初始化串口缓冲数组
byte heb0=32,heb1=32,heb2=32,heb3=32,heb4=0;
//初始化byte变量,用于串口通信
byte heb5;
while( Serial.available() >= 0){
byteNum = Serial.available();
if(byteNum == 8){
for(int i=0; i<8; i++){
buffData[i] = Serial.read();
// Serial.print(buffData[i]);
//每次读取一字节
}
// 校验包头 为0x0A ,包尾 0x0B
if(buffData[0]==0x0A && buffData[7] == 0x0B){
// Serial.println(buffData);
r = buffData[1];
g = buffData[2];
b = buffData[3];
// Serial.println(r);
// Serial.println(g);
// Serial.println(b);
//
onLight(r,g,b);
delay(5);
heb0 = buffData[4];
heb1 = buffData[5];
heb2 = buffData[6];
heb0 = heb0%256;
heb1 = heb1%256;
heb2 = heb2%256;
analogWrite(3,heb0);
analogWrite(5,heb1);
analogWrite(6,heb2);
delay(5);
}
memset(buffData, 0, sizeof buffData); //清空数组
}
else{
for(int i=0; i<byteNum; i++){
Serial.read();
}
delay(5);
}
Serial.flush(); //等待传输结束
delay(100);
}
onLight(r,g,b);
analogWrite(3,heb0);
analogWrite(5,heb1);
analogWrite(6,heb2);
delay(50);
}
void onLight(uint8_t r,uint8_t g, uint8_t b){
// strip.clear(); // Set all pixel colors to '
if(r >= 0 && r < 256 && g >= 0 && g < 256 && b >= 0 && b < 256){
for(int i=0; i<LED_COUNT; i++) { // For each pixel...
strip.setPixelColor(i, r,g,b);
strip.show();
delay(50);
}}}
1
https://gitee.com/lijiecamel/serial-code.git
git@gitee.com:lijiecamel/serial-code.git
lijiecamel
serial-code
Serial-code
master

搜索帮助